【发布时间】:2018-12-20 17:49:53
【问题描述】:
当我对数据进行子集化时,我会根据某些值或跨一组行进行子集化,如下所示:
# Subset on some values
df<-df[df$A=='some values',]
# Subset on Group of Rows
df<-df[1:10,]
但是,有没有办法将这两种方法结合起来?
我需要能够获取数据框的前 7 行,然后搜索带有条件的列,并在不同的列中返回值。
如果我有这些数据:
col_with_conditions<-c(1,2,3,4,5,1,2,3,4,5)
col_to_return<-c(10,10,10,20,20,20,10,20,10,20)
df<-data.frame(col_with_conditions,col_to_return)
col_with_conditions col_to_return
1 10
2 10
3 10
4 20
5 20
1 20
2 10
3 20
4 10
5 20
我想搜索值 1 和 2,然后返回 col_to_return 中的第一个值。在此示例中,代码将返回 10.
另一个例子:
col_with_conditions<-c(5,2,2,3,4,5)
col_to_return<-c(20,10,10,10,20,10)
df<-data.frame(col_with_conditions,col_to_return)
也会返回10。
另一个例子:
col_with_conditions<-c(5,2,4,3,4)
col_to_return<-c(20,20,20,10,20)
df<-data.frame(col_with_conditions,col_to_return)
会返回20.
但是,这个例子:
col_with_conditions<-c(5,3,4,3,4)
col_to_return<-c(20,20,20,10,20)
df<-data.frame(col_with_conditions,col_to_return)
应该返回NA,我可以在其他地方将其转换为0。有时数据框并不总是具有1 or 2. 的值
可以一步完成吗?
【问题讨论】: