对R中的每一列应用一个函数 [英] Apply a function for each pair of columns in R
本文介绍了对R中的每一列应用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
Day A1 A2 B1 B2 C1 C2
Mon 1 0 0 1 0 1
Tue 1 0 1 0 0 1
Wed 0 1 1 0 1 0
Thu 0 1 0 1 1 0
df <- data.frame(A1=c(1,1,0,0),A2=c(0,0,1,1),B1=c(0,1,1,0),B2=c(1,0,0,1),C1=c(0,0,1,1),C2=c(1,1,0,0), row.names=c('Mon','Tue','Wed','Thu'))
我希望将X1 = 1和X2 = 0的日期作为输出,按字母分类例如,对于字母A,Mon和Tue匹配标准A1 = 1和A2 = 0。
I want to get as an output the days that have have X1=1 and X2=0, classified by letter. For example, for letter A, Mon and Tue match the criteria A1=1 and A2=0.
输出为:
列表:
$A
Mon
Tue
$B
Tue
Wed
$C
Wed
Thu
或数据框: p>
Or a dataframe:
Lett Day
A Mon
A Tue
B Tue
B Wed
C Wed
C Thu
我尝试了以下内容:
对于A:
A <- df$A1 == 1 & df$A2 == 0
我会得到一个逻辑向量,如:
I would get a logical vector like:
T
T
F
F
然后将它们与初始db的日期相匹配:
Then match them with the days of the initial db:
A <- cbind(db[1], A)
并过滤TRUE值以获取输出
And filter the "TRUE" values to get the output
A
Mon
Tue
我可以为每个字母做这个,但脚本太长,问题是我可以有任意数量的字母(A,B .. Z) p>
I could do this for every letter but the script would be too long and the problem is that I could have any number of letters (A, B.. Z)
推荐答案
这是使用 split.default
的一种方式:
grped.cols <- split.default(df, substr(names(df), 1, 1))
cond <- function(x) row.names(df)[x[1] & ! x[2]]
lapply(grped.cols, cond)
# $A
# [1] "Mon" "Tue"
#
# $B
# [1] "Tue" "Wed"
#
# $C
# [1] "Wed" "Thu"
这篇关于对R中的每一列应用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文