Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.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中的数据帧中添加一个新列,该列包含每行中最频繁的值 例如考虑下面的数据文件: X[[i]] X[[i]] X[[i]] 1 1 1 1 2 1 1 2 3 1 2 2 4 0 3 0 5 3 3 3 6 0 3 0 7 4 3 4 8 4 4 4_R - Fatal编程技术网

在R中的数据帧中添加一个新列,该列包含每行中最频繁的值 例如考虑下面的数据文件: X[[i]] X[[i]] X[[i]] 1 1 1 1 2 1 1 2 3 1 2 2 4 0 3 0 5 3 3 3 6 0 3 0 7 4 3 4 8 4 4 4

在R中的数据帧中添加一个新列,该列包含每行中最频繁的值 例如考虑下面的数据文件: X[[i]] X[[i]] X[[i]] 1 1 1 1 2 1 1 2 3 1 2 2 4 0 3 0 5 3 3 3 6 0 3 0 7 4 3 4 8 4 4 4,r,R,结果将是: X[[i]] X[[i]] X[[i]] output 1 1 1 0 1 2 1 1 2 1 3 1 2 2 2 4 0 3 0 0 5 3 3 3 3 6 0 3 0 0 7 4 3 4 4 8

结果将是:

    X[[i]] X[[i]] X[[i]] output
1      1      1      0      1
2      1      1      2      1
3      1      2      2      2
4      0      3      0      0
5      3      3      3      3
6      0      3      0      0
7      4      3      4      4
8      4      4      4      4
数据帧在每次执行中的行数和列数不同。并且输出列值是数值


提前感谢。

我们可以使用
apply
循环行,并使用
Mode

cbind(df1, output = apply(df1, 1, FUN = Mode))
#  X[[i]] X[[i]] X[[i]] output
#1      1      1      1      1
#2      1      1      2      1
#3      1      2      2      2
#4      0      3      0      0
#5      3      3      3      3
#6      0      3      0      0
#7      4      3      4      4
#8      4      4      4      4
在哪里


Mode您计算的是每行的值。以下内容适用于任意数量的行和列:

mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

df$output = apply(df, 1, mode)

第1行第3列,为什么值从1更改为0?或者这是一个打字错误?
df1 <- structure(list(`X[[i]]` = c(1L, 1L, 1L, 0L, 3L, 0L, 4L, 4L), 
    `X[[i]]` = c(1L, 1L, 2L, 3L, 3L, 3L, 3L, 4L), `X[[i]]` = c(1L, 
    2L, 2L, 0L, 3L, 0L, 4L, 4L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))
mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

df$output = apply(df, 1, mode)
  V1 V2 V3 output
1  1  1  1      1
2  1  1  2      1
3  1  2  2      2
4  0  3  0      0
5  3  3  3      3
6  0  3  0      0
7  4  3  4      4
8  4  4  4      4