简体   繁体   中英

R: assigning value from one column to another

This probably has a very simple answer, but I'm having trouble figuring it out...

What is a vector-based way to take one value in the cell of one column in a dataframe, conditional on some criterion in a given row being satisfied, and assign it to a cell along the same row but in a different column? I've done it with loops over if-else statements, but I'm working with pretty big data sets, and my little laptop freezes for many minutes going through the looping conditionals.

Eg. if I have sometihng like this:

Results$TResponseCorrect[Results$rownum %in% CorrectTs$rownum] <- 1

that works fine. But what doesn't work is something like

Results$TResponseCorrect[Results$rownum %in% CorrectTs$rownum] <- Results$TCorrect

In that case I get a warning saying, "number of items to replace is not a multiple of replacement length", which I basically take to mean that it can't figure out which cell of the Results$Subject column to take.

Since your problem statement implies that all these are in the same data frame you may want:

Results$TResponseCorrect[Results$rownum %in% CorrectTs$rownum] <- 
                Results$TCorrect[Results$rownum %in% CorrectTs$rownum]

It will then have the same number of items on the LHS and the RHS of the assignment.

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