[英]Replace multiple column values in a subset dataframe in R
I want to replace some values of a subset dataframe in R like: 我想替换R中的子集数据帧的某些值,例如:
The dataframe I work with: 我使用的数据框:
sw1<- swiss[1:5, 1:4]
sw2 <- rbind(sw1,sw1)
Here is the subset as defined by some index criteria: 这是一些索引标准定义的子集:
sw2[sw2$Examination==15 & sw2$Education==12,]
where I want to replace the value for Examination and Education to 1 and 2 respectively. 我想分别将“考试”和“教育”的值分别替换为1和2。 But how can I assign values to these cells so that I get a sw2 dataframe with the correct values. 但是,如何为这些单元格分配值,以便获得具有正确值的sw2数据帧。
In your question: 在您的问题:
sw2 <- rbind(sw2,sw2)
Where does sw2
come from? sw2
来自哪里? I'm just going to assume your rbind()
should have been: 我只是假设您的rbind()
应该是:
sw2 <- rbind(sw1, sw1)
Anyway, you can replace those two columns like this: 无论如何,您可以像这样替换这两列:
sw2[sw2$Examination==15 & sw2$Education==12, c('Examination', 'Education')] <- list(1, 2)
I am isolating the columns that need to be updated with c('Examination', 'Education')
. 我隔离了需要用c('Examination', 'Education')
更新的列。 list(1, 2)
will automatically repeat for as many rows as you assign it to (two in this case). list(1, 2)
将自动重复您分配给它的尽可能多的行(在这种情况下为两行)。
Syntax is a bit funky so I would probably do something longer but easier to read. 语法有点时髦,所以我可能会做更长的时间,但更容易阅读。
m <- with(sw2, Examination == 15 & Education == 12)
sw2[m, 'Examination'] <- 1
sw2[m, 'Education'] <- 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.