1

我是 R 的新手,通过查看这个精美网站上的其他问题,我学到了很多东西!

但现在我正在处理一个我无法从其他示例中弄清楚的数据管理问题,所以我希望你能提供帮助。

我有一组从 csv 文件中读入的调查回复,并整理成一个矢量,格式如下例所示:

test <- c(
  "[1234],Bob Smith,",
  "Q-0,Male",
  "Q-1,18-25",
  "Q-2,Computer Science",
  ",",
  "[5678],Julie Lewis",
  "Q-0,Female",
  "Q-1,18-25",
  ",",
  ","
)

请注意,它","出现在自己的行上,因为我曾经处理fill=TRUEread.csv并非所有行的长度都相同的事实。另请注意,并非所有受访者都回答了所有问题。

我需要把它变成如下结构的数据框:

     ID      name         gender   age    major
1    [1234]  Bob Smith    Male     18-25  Computer Science
2    [5678]  Julie Lewis  Female   18-25  NA
   ...

似乎我无法将向量逐行读入矩阵或数据框中,因为并非所有问题都已被所有受访者回答。关于如何处理这个问题的任何建议?

4

2 回答 2

2

首先以正确的格式读取 csv 文件可能会省去很多麻烦。read.csv是一个强大的功能,应该能够处理您的数据,并且这种处理不应该是必要的。

但是,这里有:

x <- matrix(test, byrow=TRUE, ncol=5)
x <- x <- sub("Q-\\w+,", "", x)
x[x==","] <- NA
x <- cbind(matrix(unlist(strsplit(x[, 1], ",")), byrow=TRUE, ncol=2), x[, -1])
x <- as.data.frame(x, stringsAsFactors=FALSE)
names(x) <- c("ID", "Name", "Gender", "Age", "Major", "V1")

这导致:

x

      ID        Name Gender   Age            Major   V1
1 [1234]   Bob Smith   Male 18-25 Computer Science <NA>
2 [5678] Julie Lewis Female 18-25             <NA> <NA>
于 2012-06-24T05:46:27.193 回答
0

这有点笨拙,但它有效。

这是数据:

test <- c(
"[1234],Bob Smith,",
"Q-0,Male",
"Q-1,18-25",
"Q-2,Computer Science",
",",
"[5678],Julie Lewis",
"Q-0,Female",
"Q-1,18-25",
",",
"[1234],Bob Smith,",
"Q-1,18-25",
"Q-2,Computer Science",
","
)

这是操作代码:

#remove rows with just a comma
test <- test[test!=","]
#find id cases and remove the commas between the id and the name
#and add an id label
idcases <- grep("\\[.*\\]",test)
test[idcases] <- paste("id,",gsub(",","",test[idcases]),sep="")
#find id values positions and end position
idvals <- c(idcases,length(test)+1)
#generate a sequence identifier for each respondent
setid <- rep(1:(length(idvals)-1),diff(idvals))
#put the set id against each value
result1 <- paste(setid,test,sep=",")
#split the strings up and make them a data.frame
result2 <- data.frame(do.call(rbind,strsplit(result1,",")))
#get the final dataset with a reshape
final <- reshape(result2,idvar="X1",timevar="X2",direction="wide")[,-1]
#clean up the names etc
names(final) <- c("name","gender","age","major")
final$id <-  gsub("(\\[.*\\])(.*)","\\1",final$name)
final$name <- gsub("(\\[.*\\])(.*)","\\2",final$name)

这使:

> final
         name gender   age            major     id
1   Bob Smith   Male 18-25 Computer Science [1234]
5 Julie Lewis Female 18-25             <NA> [5678]
8   Bob Smith   <NA> 18-25 Computer Science [1234]
于 2012-06-24T04:35:15.447 回答