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

标签 r dataframe

我有一个 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/

相关文章:

在 R 中重新排列数据框

css - 为 Xaringan 图形和文本制作动画

python - 根据列前缀将DataFrame拆分成多个部分,并对各个部分进行运算

python - 数据帧行的快速笛卡尔求和

python - 获取 'pandas' 中对另一个变量为 True 的每个变量的比例

python - 提取数组中的连续行

r - 功能化我的代码 - 将外部创建的数据框调用到函数中

r - 根据行绘制条件颜色

r - ggplotly 无法显示 geom_line

Python Pandas pivot_table 在 pivot 之后缺少列