如果列名在另一列中,则一系列列的突变单元格
我有一个巨大的数据集,如果列名在另一列中,我想在一系列列中更改单元格值。
我知道我可以通过细胞循环,并使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为您的每一列以及数据集中的任何参考列执行此操作。
然后,您可以添加一个新的突变,或将其包含在同一突变的情况下,每个“目标”列(即)
如果您有多个源列(即
d
,则需要添加新的新列排在该列的突变的行,但是由于您的测试不包括我不会进入它,除非需要。You could do this for every column of interest as well as any reference column in your dataset.
You could then add a new mutate, or include it in the same mutate, per "target" column (i.e.)
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.我在使用current_col()中找到了我自己问题的解决方案,该解决方案在使用ifelse()中给出了当前列的名称。
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().