&引用;lapply“;在R中,不适用于每个元素 test.data
如评论中所述,您可能希望&引用;lapply“;在R中,不适用于每个元素 test.data,r,lapply,R,Lapply,如评论中所述,您可能希望匹配: test.data <- data.frame(a=seq(10),b=rep(seq(5),times=2),c=rep(seq(5),each=2)) test.data <- data.frame(lapply(test.data, as.character), stringsAsFactors = F) test.ref <- data.frame(original=seq(10),name=letters[1:10]) test.ref
匹配
:
test.data <- data.frame(a=seq(10),b=rep(seq(5),times=2),c=rep(seq(5),each=2))
test.data <- data.frame(lapply(test.data, as.character), stringsAsFactors = F)
test.ref <- data.frame(original=seq(10),name=letters[1:10])
test.ref <- data.frame(lapply(test.ref, as.character), stringsAsFactors = F)
test.match <- function (x) {
result = test.ref$name[which(test.ref$original == x)]
return(result)
}
> data.frame(lapply(test.data, test.match))
a b c
1 a a a
2 b b a
3 c c a
4 d d a
5 e e a
6 f a a
7 g b a
8 h c a
9 i d a
10 j e a
> lapply(test.data, test.match)
$a
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
$b
[1] "a" "b" "c" "d" "e"
$c
[1] "a"
这是惯用的方式
lappy
将始终返回一个普通列表。data.frame是一种特殊的列表(列向量列表)。使用注释中提到的res[],您可能需要匹配
:
test.data <- data.frame(a=seq(10),b=rep(seq(5),times=2),c=rep(seq(5),each=2))
test.data <- data.frame(lapply(test.data, as.character), stringsAsFactors = F)
test.ref <- data.frame(original=seq(10),name=letters[1:10])
test.ref <- data.frame(lapply(test.ref, as.character), stringsAsFactors = F)
test.match <- function (x) {
result = test.ref$name[which(test.ref$original == x)]
return(result)
}
> data.frame(lapply(test.data, test.match))
a b c
1 a a a
2 b b a
3 c c a
4 d d a
5 e e a
6 f a a
7 g b a
8 h c a
9 i d a
10 j e a
> lapply(test.data, test.match)
$a
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
$b
[1] "a" "b" "c" "d" "e"
$c
[1] "a"
这是惯用的方式lappy
将始终返回一个普通列表。data.frame是一种特殊的列表(列向量列表)。使用res[]我认为您的问题在于test.match
。如果您尝试对样本数据运行test.match
,您可以开始看到问题;表达式which(test.ref$original==x)
并没有达到您所期望的效果。match
函数可能更符合您的要求。要展开--test.ref$original==x
将对两个向量进行元素级比较。因此,它检查列c
,是否1==1
,2==1
,3==2
,等等,而不是搜索匹配的位置。这里需要的输出是什么?您是否正在尝试创建一个data.frame,其中每列的行数不同?这不是data.frames的工作方式。copy@MrFlick否,我试图用另一个数据帧(test.ref)中的规则替换数据帧(test.data)中的所有元素。我认为您的问题在于test.match
。如果您尝试对样本数据运行test.match
,您可以开始看到问题;表达式which(test.ref$original==x)
并没有达到您所期望的效果。match
函数可能更符合您的要求。要展开--test.ref$original==x
将对两个向量进行元素级比较。因此,它检查列c
,是否1==1
,2==1
,3==2
,等等,而不是搜索匹配的位置。这里需要的输出是什么?您是否正在尝试创建一个data.frame,其中每列的行数不同?data.frames不是这样工作的。copy@MrFlick否,我正在尝试用另一个数据帧(test.ref)中的规则替换数据帧(test.data)中的所有元素
a b c
1 a a a
2 b b a
3 c c b
4 d d b
5 e e c
6 f a c
7 g b d
8 h c d
9 i d e
10 j e e
test.mat <- as.matrix(test.data)
do.test.match <- function(mat, ref_df=test.ref){
res <- matrix(, nrow(mat), ncol(mat))
res[] <- ref_df$name[ match( c(mat), ref_df$original ) ]
return(res)
}
do.test.match(test.mat)