我有一个字符数组,它保存数据帧中某一行的列名和值。不幸的是,如果特定条目的值为零,则列名称和值不会在数组中列出。我用这些信息创建我想要的数据框架,但是我依赖于一个"for循环“。
我想利用 普莱尔 来避免下面的工作代码中的for循环。
types <- c("one", "two", "three") # My data
entry <- c("one(1)", "three(2)") # My data
values <- function(entry, types)
{
frame<- setNames(as.data.frame(matrix(0, ncol = length(types), nrow = 1)), types)
for(s1 in 1:length(entry))
{
name <- gsub("\\(\\w*\\)", "", entry[s1]) # get name
quantity <- as.numeric(unlist(strsplit(entry[s1], "[()]"))[2]) # get value
frame[1, which(colnames(frame)==name)] <- quantity # store
}
return(frame)
}
values(entry, types) # This is how I want the output to look我尝试了下面的方法来拆分数组,但是我想不出如何正确地返回单个行。
types <- c("one", "two", "three") # data
entry <- c("one(1)", "three(2)") # data
frame<- setNames(as.data.frame(matrix(0, ncol = length(types), nrow = 1)), types)
array_split <- function(entry, frame){
name <- gsub("\\(\\w*\\)", "", entry) # get name
quantity <- as.numeric(unlist(strsplit(entry, "[()]"))[2]) # get value
frame[1, which(colnames(frame)==name)] <- quantity # store
return(frame)
}
adply(entry, 1, array_split, frame),我应该考虑一些类似累积量的东西吗?我想尽快完成这个操作.
发布于 2014-11-21 17:14:38
我不知道你为什么不做这样的事情:
frame <- setNames(rep(0,length(types)),types)
a <- as.numeric(sapply(strsplit(entry,"[()]"),`[[`,2))
names(a) <- gsub("\\(\\w*\\)", "", entry)
frame[names(a)] <- agsub和strsplit都已经向量化了,因此在任何地方都不需要显式循环。您只需要使用sapply来提取strsplit结果的第二个元素。剩下的只是常规的索引。
https://stackoverflow.com/questions/27066627
复制相似问题