简体   繁体   中英

How to use apply() to add a new column based on a condition in a diiferent column in R

I am trying to create a new column based on values from a different column using R. Here is an example of what the data.frame looks like:

df<-data.frame(well=c("A01","A02","A03","B01","B02","B03","C01","C02","C03"))
df 
  well
1  A01
2  A02
3  A03
4  B01
5  B02
6  B03
7  C01
8  C02
9  C03

I am new to using the apply() function so I am wondering how to write a code that would make a new column named "row" based of the values in the "well column.

What I am trying to achieve would look like this:

df2<-data.frame(well=c("A01","A02","A03","B01","B02","B03","C01","C02","C03"),
row=c("1","1","1","2","2","2","3","3","3")
df2
  well  row
1  A01   1
2  A02   1
3  A03   1
4  B01   2
5  B02   2
6  B03   2
7  C01   3
8  C02   3
9  C03   3

The letter in the "well" column is what the value in the "row" column is dependent and that is what is causing me the issue. So "Axx" would yield a "1", "Bxx" would yield 2, and so on.

Here is one idea. We can use gsub to get the letter from the well column, convert to factor, and then convert to numeric.

# Create example data frame
df<-data.frame(well=c("A01","A02","A03","B01","B02","B03","C01","C02","C03"),
               stringsAsFactors = FALSE)

df$row <- as.numeric(factor(gsub("[0-9]*", "", df$well)))

df
#   well row
# 1  A01   1
# 2  A02   1
# 3  A03   1
# 4  B01   2
# 5  B02   2
# 6  B03   2
# 7  C01   3
# 8  C02   3
# 9  C03   3

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