我正在尝试编写一些将列名用作结果名的代码
我现在可以循环浏览文件列表并提取数据,因为文件的结构始终相同。但是我希望能够在不同大小的数据帧上使用相同的方法。
我的输入文件如下:
aus = structure(list(X = c("John", "Frank", "Judy", "Tom", "Margaret",
"Jane"), Sydney = c(79L, 21L, 96L, 80L, 51L, 69L), Melbourne = c(17L,
13L, 42L, 86L, 2L, 69L), Perth = c(82L, 71L, 63L, 39L, 68L, 19L
), Adelaide = c(37L, 99L, 59L, 23L, 35L, 26L), Canberra = c(61L,
41L, 23L, 78L, 22L, 27L), Brisbane = c(79L, 71L, 19L, 45L, 85L,
20L)), class = "data.frame", row.names = c(NA, -6L))
我可以使用以下方法获得Judy的结果:
files = c("aus.csv")
read.data = function(files)
{
tmp = read.csv(list[i], row.names = 1)
Sydney = as.numeric(tmp["Judy",1])
Melbourne = as.numeric(tmp["Judy",2])
Perth = as.numeric(tmp["Judy",3])
Adelaide = as.numeric(tmp["Judy",4])
Canberra = as.numeric(tmp["Judy",5])
Brisbane = as.numeric(tmp["Judy",6])
results = c(list[i], Judy, Sydney, Melbourne, Perth, Adelaide, Canberra, Brisbane)
return(results)
}
list = files
datalist = as.list(1)
for(i in 1:length(list))
{
temp=vector()
datalist[[i]] = try(read.data(list[i]))
if(is.null(dim(temp)[1])){next}
}
dataframe = do.call(rbind, datalist)
colnames(dataframe) = c("report", "name", "Sydney", "Melbourne", "Perth", "Adelaide", "Canberra", "Brisbane")
我想用一些可以查找名称的代码代替本节(这样就不会硬编码了):
Sydney = as.numeric(tmp["Judy",1])
Melbourne = as.numeric(tmp["Judy",2])
Perth = as.numeric(tmp["Judy",3])
Adelaide = as.numeric(tmp["Judy",4])
Canberra = as.numeric(tmp["Judy",5])
Brisbane = as.numeric(tmp["Judy",6])
results = c(list[i], Judy, Sydney, Melbourne, Perth, Adelaide, Canberra, Brisbane)
对于我的一生,我无法解决自己需要的循环。有人可以指出正确的方向吗?
我正在寻找相同的输出,只是一种更动态的方式来从名称中收集结果名称。
results = structure(c("aus.csv", "Judy", "96", "42", "63", "59", "23",
"19"), .Dim = c(1L, 8L), .Dimnames = list(NULL, c("report", "name",
"Sydney", "Melbourne", "Perth", "Adelaide", "Canberra", "Brisbane"
)))
答案 0 :(得分:0)
希望这会有所帮助
library(tidyverse)
results = aus %>%
filter(X == "Judy") %>% # filter only John
mutate(report = "aus.csv") %>% # include report name
select(report, name, everything()) # reorder columns
如果要将输出作为字符或列表,请将%>% unlist
或%>% list
添加到上述链中。