有点乱,我认为可能有更好的方法,但你可以试试
library(dplyr)
library(tibble)
df <- read.table(text = "label1 label2 label3 label#
value1 value4 value7 label2
value2 value5 value8 label1
value3 value6 value9 label3", h = T)
df %>%
rowwise %>%
rownames_to_column(., "row") %>%
mutate(currentvalue = .[[which(rownames(.) == row),which(names(.) == label)]])
row label1 label2 label3 label currentvalue
<chr> <chr> <chr> <chr> <chr> <chr>
1 1 value1 value4 value7 label2 value4
2 2 value2 value5 value8 label1 value2
3 3 value3 value6 value9 label3 value9
当我用read.table读取你的数据时,label#变成label。
列名label#
names(df)[4] <- "label#"
df %>%
rowwise %>%
rownames_to_column(., "row") %>%
mutate(currentvalue = .[[which(rownames(.) == row),which(names(.) == 'label#')]])
row label1 label2 label3 `label#` currentvalue
<chr> <chr> <chr> <chr> <chr> <chr>
1 1 value1 value4 value7 label2 label2
2 2 value2 value5 value8 label1 label1
3 3 value3 value6 value9 label3 label3
使用基础 R
x <- match(df$label, names(df))
y <- 1:nrow(df)
z <- data.frame(y, x)
df$currentvalue <- apply(z,1, function(x) df[x[1],x[2]])
时间检查
microbenchmark::microbenchmark(
a = {
df %>%
rowwise %>%
rownames_to_column(., "row") %>%
mutate(currentvalue = .[[which(rownames(.) == row),which(names(.) == label)]])
},
b = {
x <- match(df$label, names(df))
y <- 1:nrow(df)
z <- data.frame(y, x)
df$currentvalue <- apply(z,1, function(x) df[x[1],x[2]])
}
)
Unit: microseconds
expr min lq mean median uq max neval cld
a 6157.8 6861.95 8773.098 7465.75 9367.1 26232.8 100 b
b 360.6 399.75 692.073 488.40 666.9 4225.0 100 a