Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中列的名称_R - Fatal编程技术网

R中列的名称

R中列的名称,r,R,我有一个每月降水量的位置和数值表 我需要添加一个新列,其中包含每个位置降雨量最大的月份的名称 我试着这么做: cbind(rainfall, max_month = apply(rainfall[,3:11],1,which.max)) 但我只得到列的编号,我需要列的名称。 我明白了: [1] 5 5 5 5 5 5 5 5 4 4 5 5 5 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5

我有一个每月降水量的位置和数值表

我需要添加一个新列,其中包含每个位置降雨量最大的月份的名称

我试着这么做:

cbind(rainfall, max_month = apply(rainfall[,3:11],1,which.max))
但我只得到列的编号,我需要列的名称。 我明白了:

[1] 5 5 5 5 5 5 5 5 4 4 5 5 5 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
 [59] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 4 4 5 5 4 5 5 5 5 5 5 5 5 5 5 5 5
[117] 5 5 5 5 5 5 5 5 5 6 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 4 4
我试图添加name函数和colnames函数,但这两个函数都没有用

names(apply(rainfall[,3:11],1,(which.max))) 
谢谢


您可能需要以下内容:

names(rainfall[,3:11])[apply(rainfall[,3:11],1,which.max)]
在这里,通过子集
名称(降雨)
向量,将列id转换为名称。请注意,重复索引,例如
c(5,5,5,5)
会重复提取的值


使用
dplyr
的替代方法:

library(dplyr)
library(mtcars)
mtcars %>% 
    gather(month, precip_value, disp, hp, drat, wt) %>% 
    group_by(gear) %>% 
    summarise(max_month = month[which.max(precip_value)])

请注意,此方法使用了
mtcars
数据集,因为您的示例不可复制。这里,
gear
将是您的站点id。诀窍是使用
collect
将数据从宽格式重新构造为长格式,然后使用
group\u将每个站点的数据按
拆分,然后使用
summary
确定最大月份。值得深思的是,@sotos的答案相当优雅。

您可能需要以下几点:

names(rainfall[,3:11])[apply(rainfall[,3:11],1,which.max)]
在这里,通过子集
名称(降雨)
向量,将列id转换为名称。请注意,重复索引,例如
c(5,5,5,5)
会重复提取的值


使用
dplyr
的替代方法:

library(dplyr)
library(mtcars)
mtcars %>% 
    gather(month, precip_value, disp, hp, drat, wt) %>% 
    group_by(gear) %>% 
    summarise(max_month = month[which.max(precip_value)])

请注意,此方法使用了
mtcars
数据集,因为您的示例不可复制。这里,
gear
将是您的站点id。诀窍是使用
collect
将数据从宽格式重新构造为长格式,然后使用
group\u将每个站点的数据按
拆分,然后使用
summary
确定最大月份。值得思考的是,@sotos的答案非常优雅。

最好的方法是通过
max.col
。您应始终避免对data.frames应用

names(rainfall)[max.col(rainfall[3:11])]

最好的方法是通过
max.col
。您应始终避免对data.frames应用

names(rainfall)[max.col(rainfall[3:11])]

您需要
应用(df,1,函数(i)名称(i[which.max(i)])
。但是,请检查函数
max.col
,您能让您的答案重现吗?这将使您更容易获得帮助,特别是在为您提供替代解决方案时。您需要
应用(df,1,函数(i)名称(i[which.max(i)])
。但是,请检查函数
max.col
,您能让您的答案重现吗?这将使它更容易帮助您,特别是为您提供替代解决方案。很好,我不知道这个功能。在R:)中总是有更多的东西需要学习。很好,我不知道这个函数。在R中总是有更多的东西需要学习。这正是我所需要的:)这正是我所需要的:)