1

我有大量巨大的数据框。通常在这些数据框中,我有一组名称相似的列按顺序出现。以下是此类数据框的简化版本:

> tmp <- data.frame(ID = 1:25,
    Item1 = sample(x = 1:4, size = 25, replace = TRUE),
    Item2 = sample(x = 1:4, size = 25, replace = TRUE),
    Item3 = sample(x = 1:4, size = 25, replace = TRUE),
    Item4 = sample(x = 1:4, size = 25, replace = TRUE),
    Item5 = sample(x = 1:4, size = 25, replace = TRUE),
    Item6 = sample(x = 1:4, size = 25, replace = TRUE),
    Item7 = sample(x = 1:4, size = 25, replace = TRUE),
    Quest = rep(x = 20, times = 25))

我需要找到一种方法来通过它们的名称范围而不是它们的位置来索引这些列。假设我需要从 to 索引Item4Item7。我可以执行以下操作:

> tmp[ , c("Item4", "Item5", "Item6", "Item7")]

当您有数百个具有相似名称的列时,这不是很好。我想做类似的事情:

> tmp[ , c("Item4":"Item7")]

但它会抛出一个错误:

Error in "Item1":"Item7" : NA/NaN argument
In addition: Warning messages:
1: In `[.data.frame`(tmp, , c("Item1":"Item7")) :
  NAs introduced by coercion
2: In `[.data.frame`(tmp, , c("Item1":"Item7")) :
  NAs introduced by coercion

此外,我想使用这种索引来操作列的属性,例如(使用前一种方法列出所有列名)

> labels.Item4to7 <- c("Disagree", "Somewhat disagree",
  "Somewhat agree", "Agree")
> tmp[ , c("Item4", "Item5", "Item6", "Item7")] <- lapply(tmp[ , c("Item4",
  "Item5", "Item6", "Item7")], factor, labels = labels.Item4to7)

但是将列名的范围定义为Item4:Item7.

先感谢您。

4

2 回答 2

3

使用功能

tmp[,which(names(tmp)=="Item4"):which(names(tmp)=="Item7")]

可以通过以下方式更改第 4 项到第 7 项的值:

labels.Item4to7 <- c("Disagree", "Somewhat disagree",
  "Somewhat agree", "Agree")
tmp[,which(names(tmp)=="Item4"):which(names(tmp)=="Item7")]<-
   lapply(tmp[,which(names(tmp)=="Item4"):which(names(tmp)=="Item7")],
   factor,labels=labels.Item4to7)
于 2015-02-16T23:11:33.437 回答
2

你可以使用paste

tmp[, paste0("Item", 4:7)]
于 2015-02-16T22:20:52.493 回答