如果列名在另一列中,则一系列列的突变单元格

发布于 2025-02-11 21:01:21 字数 498 浏览 2 评论 0原文

我有一个巨大的数据集,如果列名在另一列中,我想在一系列列中更改单元格值。

我知道我可以通过细胞循环,并使用ifelse,但这很快就会变得非常慢。我到了使用突变()和跨(),但无法弄清楚如何使用列名制作逻辑。

如果有人可以提出类似的问题(我找不到的问题!),我会很感激,如果可能的话,我将使用淡淡的问题。

数据集的示例和嵌套循环的示例:

a <- c(1,2,3,4)
b <- c(5,6,7,8)
c <- c(9,10,11,12)
d <- c("a","b","c","none")
test <- data.frame(a,c,b,d)

for(column in 1:3){
    for(row in 1:nrow(test)){
        test[row,column] <- ifelse(names(test)[column] == test$d[row], -99, test[row, column])
    }
}

I have a huge dataset where I would like to change a cell value in a range of columns, if the column name is in another column.

I know I can loop through cells, and use ifelse, but this becomes very slow very soon, it seems. I got as far as using mutate() and across() but cannot work out how to make a logical with the column name.

I would be grateful if someone could suggest a vectorized approach, or point me to a similar question (which I was unable to find!), using tidyverse if possible.

Example of a dataset and the nested for loops:

a <- c(1,2,3,4)
b <- c(5,6,7,8)
c <- c(9,10,11,12)
d <- c("a","b","c","none")
test <- data.frame(a,c,b,d)

for(column in 1:3){
    for(row in 1:nrow(test)){
        test[row,column] <- ifelse(names(test)[column] == test$d[row], -99, test[row, column])
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

友欢 2025-02-18 21:01:22

您可以为您的每一列以及数据集中的任何参考列执行此操作。

library(tidyverse)

test %>% 
  mutate(a = case_when(
    d == names(test)[1] ~ -99,
    T ~ a
  ))

然后,您可以添加一个新的突变,或将其包含在同一突变的情况下,每个“目标”列(即)

test %>% 
  mutate(a = case_when(
    d == names(test)[1] ~ -99,
    T ~ a
  )) %>% 
  mutate(b = case_when(
    d == names(test)[2] ~ -99,
    T ~ b
  ))

如果您有多个源列(即d,则需要添加新的新列排在该列的突变的行,但是由于您的测试不包括我不会进入它,除非需要。

You could do this for every column of interest as well as any reference column in your dataset.

library(tidyverse)

test %>% 
  mutate(a = case_when(
    d == names(test)[1] ~ -99,
    T ~ a
  ))

You could then add a new mutate, or include it in the same mutate, per "target" column (i.e.)

test %>% 
  mutate(a = case_when(
    d == names(test)[1] ~ -99,
    T ~ a
  )) %>% 
  mutate(b = case_when(
    d == names(test)[2] ~ -99,
    T ~ b
  ))

If you have multiple source columns (i.e. Columns like d, then you would need to add new rows to your mutates that account for that column, however since your test does not include that I won't get into it unless required.

软的没边 2025-02-18 21:01:21

我在使用current_col()中找到了我自己问题的解决方案,该解决方案在使用ifelse()中给出了当前列的名称。

test %>% mutate(across(c(a, b, c), ~ifelse(cur_column() == d, -99, .)))

I found the solution to my own question in using current_col() which gives the name of the current column in an across()function, using ifelse().

test %>% mutate(across(c(a, b, c), ~ifelse(cur_column() == d, -99, .)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文