基于列和行的子集

har*_*l.c 1 r dataframe

我有一个这样的R数据帧包含不同时间的价格

     product_1  product_2  product_3  product_4  product_5
 t1  10         10         10         0          14
 t2  20         0          50         15         15
 t3  30         0          60         12         12
 t4  40         14         15         5          0
Run Code Online (Sandbox Code Playgroud)

在特定时间= t2之后,对于价格为0且至少一次的产品,什么查询会给我所有包含价格的表格?基本上是基于行和列条件的数据帧的子集.

     product_2  product_5
 t1  10         14
 t2  0          15
 t3  0          12
 t4  14         0
Run Code Online (Sandbox Code Playgroud)

Ben*_*ker 5

读取数据:

dd <- read.table(header=TRUE,text="
    product_1  product_2  product_3  product_4  product_5
 t1  10         10         10         0          14
 t2  20         0          50         15         15
 t3  30         0          60         12         12
 t4  40         14         15         NA          0")
Run Code Online (Sandbox Code Playgroud)

查找关键时间索引:

which.time <- which(rownames(dd)=="t2")
Run Code Online (Sandbox Code Playgroud)

用于标识要保留的列的函数(也可以使用any(na.omit(tail(x,-which.time)==0)); na.omit()是必要的,以避免NAs在逻辑向量中结束,指定要保留哪些列,这将导致稍微模糊的undefined columns selected错误...

keepvar <- function(x) {
    any(na.omit(x[-(1:(which.time-1))])==0)
}
Run Code Online (Sandbox Code Playgroud)

现在做实际选择:

dd[sapply(dd,keepvar)]
Run Code Online (Sandbox Code Playgroud)