简体   繁体   中英

Replace specific values in a column in data frame

I really apologize for such a basic question and I have spent 20 minutes trying to figure this out. Example:

x <- sample(c("1","2"), 100, replace = TRUE)
y <- sample(c("3","4"), 100, replace = TRUE)
xy <- cbind(x,y)

Now I want to replace all "2"s with "0"s in the x column. On my real data, I need to recode all the females coded as "2" as "0".

I have tried:

xy$x[,xy$x == 2] <- 0

xy[xy$x== 2] <- 0

women <- xy$x== 2
xy[women,] <- 0

Neither of these work. The first two give an error, the last one replaces the whole row with zeros. I have searched a lot on this site but there has to be a very simple solution (not that the difficult worked anyway).

EDIT:

My apologies for using a sample not equal to my actual issue. How do I do it with this sample?

x <- sample(c("1","2"), 100, replace = TRUE)
y <- sample(c("3","4"), 100, replace = TRUE)
xy <- cbind(x,y)

Thanks!

There are several problems:

  • xy is matrix but the code is using $ which is for data frames.

  • if xy were a data frame then xy$x is one dimensional but the code in the question is attempting to index it with 2 dimeensions

  • the code in the question using women is attempting to set the entire row to 0

  • to make the example reproducible the question should include set.seed so that the same random numbes are used each time it is invoked

This variation of the code in the question works.

If you are using a version of R that earlier than R 4.0 it is important to use stringAsFactors=FALSE ; however, for later versions that argument is not needed although it won't hurt if you leave it in.

xy <- as.data.frame(xy, stringsAsFactors = FALSE)
xy$x[xy$x == 2] <- 0

For the code involving women assuming again that xy is a data frame:

women <- xy$x== 2
xy[women, "x"] <- 0

If xy is a matrix as in the question then this works:

xy[xy[, "x"] == 2, "x"] <- 0

This works whether xy is a matrix or data frame and returns a data.frame:

transform(xy, x = replace(x, x == 2, 0))

or

transform(xy, x = ifelse(x == 2, 0, x))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM