R 求数据帧中一系列变量的最大值
我有以下数据框:R 求数据帧中一系列变量的最大值,r,R,我有以下数据框: id cluster username 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 1 268672 Type 1 Vlaam 0 0 0 0 0 0 5896 18976 13552 20508 106939 2 351003 Type 2 WikiCleanerBot 0 0 0 0 0
id cluster username 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
1 268672 Type 1 Vlaam 0 0 0 0 0 0 5896 18976 13552 20508 106939
2 351003 Type 2 WikiCleanerBot 0 0 0 0 0 0 0 17049 8468 22834 7470
2012 2013 2014 2015 2016
1 83874 97447 59677 88661 41133
2 11219 83245 28015 40464 25053
我需要创建最后一个变量,告诉我2001年、2002年的变量是什么。。。2016系列的每一行都包含该系列的max。我写这段代码:
cluster$yearMod <- apply(cluster,1,function(x) {
years <- x[4:19]
as.numeric(names(years)[match(max(years),years)])
})
这绝对不是正确的值,是2011年和2013年
你能帮我吗?如果是
max
元素,那么我们可以使用max.col
。使用grepl
('i1')创建数字列名的逻辑索引,然后将基于数据集的'i1'子集(df1[i1]
)为具有max.col
的每一行获取max
值的索引,并使用该索引获取相应的列名
i1 <- grepl("[0-9]+$", names(df1))
df1$newVar <- names(df1)[i1][max.col(df1[i1], "first")]
df1$newVar
#[1] "2011" "2013"
数据
df1如果您需要模式,请使用table
对不起,我的问题没有正确表述,我需要的是最大值,但不是模式。你能把复制的旗子移走吗?
i1 <- grepl("[0-9]+$", names(df1))
df1$newVar <- names(df1)[i1][max.col(df1[i1], "first")]
df1$newVar
#[1] "2011" "2013"
names(df1)[i1][apply(df1[i1], 1, which.max)]
#[1] "2011" "2013"
df1 <- structure(list(id = c(268672L, 351003L), cluster = c("Type 1",
"Type 2"), username = c("Vlaam", "WikiCleanerBot"), `2001` = c(0L,
0L), `2002` = c(0L, 0L), `2003` = c(0L, 0L), `2004` = c(0L, 0L
), `2005` = c(0L, 0L), `2006` = c(0L, 0L), `2007` = c(5896L,
0L), `2008` = c(18976L, 17049L), `2009` = c(13552L, 8468L),
`2010` = c(20508L,
22834L), `2011` = c(106939L, 7470L), `2012` = c(83874L, 11219L
), `2013` = c(97447L, 83245L), `2014` = c(59677L, 28015L),
`2015` = c(88661L,
40464L), `2016` = c(41133L, 25053L)), .Names = c("id", "cluster",
"username", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
"2016"), row.names = c("1", "2"), class = "data.frame")