我已经看到了这个解决方案的几个线程,但我奋力实现它们。我有带有介绍横跨上面列的东风,然后我有样本与被描述分组数据的列表。我需要提取其中的描述相匹配的列名的值。
我曾尝试使用匹配,cbind,sapply ...等不同的解决方案,但得到有关无效型(矩阵)或有重复的行名错误。
df1
#row description sample ball square circle
1 ball 1a .78 .04 .22
2 ball 7b3 .32 .33 .33
3 square aaabc .02 .90 .05
4 circle ggg3 .05 .04 .90
5 circle 44 .01 .25 .70
我的输出是:
df2
#row description sample value
1 ball 1a .78
2 ball 7b3 .32
3 square aaabc .90
4 circle ggg3 .90
5 circle 44 .70
然后取这一步,我会再过滤它
df2 %>%
filter(value < .9) %>%
select(description, sample, value)
导致:
#row description sample value
1 ball 1a .78
2 ball 7b3 .32
3 circle 44 .70
我知道这是一个重复的,我只是一片空白,为什么我不能得到解决与此数据集工作。
我们可以用一个行/列的索引来提取与“说明”列值match
列名的值
m1 <- cbind(seq_len(nrow(df1)), match(df1$description, names(df1)[3:5]))
data.frame(df1[1:3], value = df1[3:5][m1])
# description sample ball value
#1 ball 1a 0.78 0.78
#2 ball 7b3 0.32 0.32
#3 square aaabc 0.02 0.90
#4 circle ggg3 0.05 0.90
#5 circle 44 0.01 0.70
或与tidyverse
library(tidyverse)
df1 %>%
rowwise %>%
transmute(description, sample, value = get(description))
# A tibble: 5 x 3
# description sample value
# <chr> <chr> <dbl>
#1 ball 1a 0.78
#2 ball 7b3 0.32
#3 square aaabc 0.9
#4 circle ggg3 0.9
#5 circle 44 0.7
df1 <- structure(list(description = c("ball", "ball", "square", "circle",
"circle"), sample = c("1a", "7b3", "aaabc", "ggg3", "44"), ball = c(0.78,
0.32, 0.02, 0.05, 0.01), square = c(0.04, 0.33, 0.9, 0.04, 0.25
), circle = c(0.22, 0.33, 0.05, 0.9, 0.7)), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5"))
看来你有可能性的百分比。所以,你基本上是试图提取与发生的可能性最高,像那些3行中提取每行的最大值列。所以:
首先,我们创建一个函数来提取3列中每行最大
funcionMax <- function(unDf) {
numFilas <- nrow(unDf)
vectorMax <- vector()
for(i in 1:numFilas)
{
vectorMax[i]<- max(unDf[i,1],unDf[i,2],unDf[i,3])
}
vectorMax
}
然后,我们子集仅与3列处理,并应用新的功能:
vectorFuncionMax <- df %>% select(ball,square,circle) %>% funcionMax
cbind(df,vectorFuncionMax)
仅此而已。别客气。