I want to replace some values of a subset dataframe in R like:
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. But how can I assign values to these cells so that I get a sw2 dataframe with the correct values.
In your question:
sw2 <- rbind(sw2,sw2)
Where does sw2
come from? I'm just going to assume your rbind()
should have been:
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')
. list(1, 2)
will automatically repeat for as many rows as you assign it to (two in this case).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.