gpt4 book ai didi

r - 如何在 R data.frame 中创建组合变量?

转载 作者:行者123 更新时间:2023-12-04 11:56:17 25 4
gpt4 key购买 nike

我有一个 data.frame,它有几个零值的变量。我需要构造一个额外的变量,它会返回每个观察值不为零的变量组合。例如。

df <- data.frame(firm = c("firm1", "firm2", "firm3", "firm4", "firm5"),
A = c(0, 0, 0, 1, 2),
B = c(0, 1, 0, 42, 0),
C = c(1, 1, 0, 0, 0))

现在我想生成新变量:
df$varCombination <- c("C", "B-C", NA, "A-B", "A")

我想到了这样的事情,这显然不起作用:
for (i in 1:nrow(df)){
df$varCombination[i] <- paste(names(df[i,2:ncol(df) & > 0]), collapse = "-")
}

最佳答案

这可能可以使用 apply(df, 1, fun) 轻松解决,但这里是为了性能而尝试解决这一列问题而不是行问题(我曾经看到@alexis_laz做过类似的事情,但现在找不到)

## Create a logical matrix
tmp <- df[-1] != 0
## or tmp <- sapply(df[-1], `!=`, 0)

## Prealocate result
res <- rep(NA, nrow(tmp))

## Run per column instead of per row
for(j in colnames(tmp)){
res[tmp[, j]] <- paste(res[tmp[, j]], j, sep = "-")
}

## Remove the pre-allocated `NA` values from non-NA entries
gsub("NA-", "", res, fixed = TRUE)
# [1] "C" "B-C" NA "A-B" "A"

在更大的数据集上的一些基准
set.seed(123)
BigDF <- as.data.frame(matrix(sample(0:1, 1e4, replace = TRUE), ncol = 10))

library(microbenchmark)

MM <- function(df) {
var_names <- names(df)[-1]
res <- character(nrow(df))
for (i in 1:nrow(df)){
non_zero_names <- var_names[df[i, -1] > 0]
res[i] <- paste(non_zero_names, collapse = '-')
}
res
}

ZX <- function(df) {
res <-
apply(df[,2:ncol(df)]>0, 1,
function(i)paste(colnames(df[, 2:ncol(df)])[i], collapse = "-"))
res[res == ""] <- NA
res
}

DA <- function(df) {
tmp <- df[-1] != 0
res <- rep(NA, nrow(tmp))

for(j in colnames(tmp)){
res[tmp[, j]] <- paste(res[tmp[, j]], j, sep = "-")
}
gsub("NA-", "", res, fixed = TRUE)
}


microbenchmark(MM(BigDF), ZX(BigDF), DA(BigDF))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# MM(BigDF) 239.36704 248.737408 253.159460 252.177439 255.144048 289.340528 100 c
# ZX(BigDF) 35.83482 37.617473 38.295425 38.022897 38.357285 76.619853 100 b
# DA(BigDF) 1.62682 1.662979 1.734723 1.735296 1.761695 2.725659 100 a

关于r - 如何在 R data.frame 中创建组合变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com