如何使用apply()根据R中不同列中的条件添加新列

时间:2019-02-01 18:30:03

标签: r apply

我正在尝试使用R根据来自不同列的值创建一个新列。这是data.frame外观的示例:

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

我对使用apply()函数是陌生的,所以我想知道如何编写代码,以便根据“井”列中的值创建一个名为“行”的新列。

我想要实现的目标如下:

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

“井”(well)列中的字母是“行”(row)列中的值所依赖的,这就是导致我出现此问题的原因。因此,“ Axx”将产生“ 1”,“ Bxx”将产生2,依此类推。

1 个答案:

答案 0 :(得分:0)

这是一个主意。我们可以使用gsubwell列中获取字母,转换为因数,然后转换为数字。

# 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