我想找到列总和最大的列.我想的是:
threeLargest = colnames(sort(colSums(data[,2:length(data)]),
decreasing = TRUE)[1:3])
Run Code Online (Sandbox Code Playgroud)
但colnames只是给出NULL了sort(colSums...命令.
原因是我希望能够引用列中的值并绘制它.我认为必须有一个更多面向R的解决方案,而不是循环遍历列并保持最大的计数.
我有example_csv_file.csv:
date,column1,column2,column3,column4
2013-12-09,0,0,0,2
2013-12-10,0,0,0,2
2013-12-11,0,0,0,2
2013-12-12,0,0,0,2
2013-12-13,0,0,0,2
2013-12-14,0,1,7,2
2013-12-15,2,15,36,2
2013-12-16,5,10,28,2
2013-12-17,1,2,39,2
2013-12-18,2,3,34,2
Run Code Online (Sandbox Code Playgroud)
我以这种方式导入:
data = read.csv(file = 'example_csv_file.csv', header = TRUE, sep = ",")
Run Code Online (Sandbox Code Playgroud)
我可以按列总和对列进行排序,然后获取前三个:
threeLargest = sort(colSums(data[,2:length(data)]), decreasing = TRUE)[1:3]
Run Code Online (Sandbox Code Playgroud)
这给出了:
> threeLargest
column3 column2 column4
144 31 20
Run Code Online (Sandbox Code Playgroud)
但我需要获取列名,因为我需要在绘制其值时引用列.就像这样:
plot(data[,'column3'])
Run Code Online (Sandbox Code Playgroud)
并且最好有一个我可以在循环中引用的顶部列表,如下所示:
plot(data[,namesOfThreeLargest[1]], type = 'n')
color = 1
for (column in namesOfThreeLargest)
{
lines(data[,column], col = color)
color = color + 1
}
legend("topleft", inset=.05, lty = 1, namesOfThreeLargest, col = seq(color))
Run Code Online (Sandbox Code Playgroud)
如果我能以一种整洁的方式获得列的编号,我可以这样得到它的名称:
columnWithLargestColSum = colnames(data)[4]
Run Code Online (Sandbox Code Playgroud)
我尝试过以不同的方式导入文件,例如read.table(file =...,read.data.frame(file =...和as.matrix(read.csv(file =...,看看是否colnames有效,但事实并非如此.实际上colSums甚至不适用于那个,as.matrix因为条目是该方法的字符串.
谢谢!
编辑:
这是我采用的解决方案:
我用order()从里斯Meys,我用names()从阿难Mahto(见下他们的解决方案):
colCount = colSums(data[-1])
topThreeIds = order(colCount,decreasing=TRUE)[1:3] + 1 # From Joris
topThreeCols = names(data[topIds]) # From Ananda
Run Code Online (Sandbox Code Playgroud)
注意+ 1在第二行,因为我正在跳过date第一行中的列.通过在第二行中添加一个,我得到了我想要的列的实际id.
多谢你们!
如果您查看步骤str的输出colSums,您会发现它只是一个命名向量,而不是任何带有“列”的内容:
str(sort(colSums(data[,2:length(data)]),
decreasing = TRUE)[1:3])
# Named num [1:3] 144 31 20
# - attr(*, "names")= chr [1:3] "column3" "column2" "column4"
Run Code Online (Sandbox Code Playgroud)
因此,如果您想要“名称”,则应该将命令包装在names而不是colnames.
换句话说:
namesOfThreeLargest <- names(threeLargest)
Run Code Online (Sandbox Code Playgroud)
从那里,现在我看到你只想做多线图,你可以看看matplot,例如:
matplot(data[, namesOfThreeLargest], type="l")
Run Code Online (Sandbox Code Playgroud)