简体   繁体   中英

R: subtract 1 from specific column, based on value other column

I'm trying do a basic operation (let's say, subtract 1) on some column, referenced by the value of another column (let's say the first column). For example: for a given row, the value in the first column is equal to 5. Then I want to subtract 1 from the same row, column 5.

Data looks like

tmp <- data.frame(replicate(5,sample(2:5,5,rep=TRUE)))

Of course, I can achieve this by a multiple row code, each time selecting a subsample of the total rows, satisfying a certain condition, but I'm sure this operation could be performed more clean and dynamically.

Additional question: is there an easy way to reference in the same manner to column names, rather than the index. For example the column name "S5"? Easiest way is through names(tmp), and then match the name of the column and use the index of names, or can you think of an easier way?

Any suggestions?

So the column index of the element is in the first column of the row:

for (i in 1:nrow(tmp)) tmp[i, tmp[i,1]] <- tmp[i, tmp[i,1]] - 1 

It also can work if in the fist column are the names of the columns as character (not as factor!):

tmp <- data.frame(cInd=c("A", "B", "C"), A=1:3, B=11:13, C=21:23,
          stringsAsFactors = FALSE)
for (i in 1:nrow(tmp)) tmp[i, tmp[i,1]] <- tmp[i, tmp[i,1]] - 1 

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