在R数据帧中用行总和创建新列

问题描述 投票:1回答:2

我正在尝试在R中做一些我认为非常简单的事情:添加一个带有总计的新列。

我创建了一个新的数据集,然后遵循此suggestion,但事实证明,它计算出的总和是错误的。然后,我遵循了另一种有效的方法,但无法将结果附加为列。

IUS_12_1_toy <- c(2,4,4)
IUS_12_2_toy <- c(4,5,4)
IUS_12_3_toy <- c(3,4,4)
IUS_12_4_toy <- c(4,5,3)
IUS_12_5_toy <- c(4,4,4)
IUS_12_6_toy <- c(2,5,3)
IUS_12_7_toy <- c(4,5,4)
IUS_12_8_toy <- c(4,4,4)
IUS_12_9_toy <- c(3,4,4)
IUS_12_10_toy <- c(2,3,4)
IUS_12_11_toy <- c(3,4,2)
IUS_12_12_toy <- c(1,4,2)

IUS_12_toy <- data.frame(IUS_12_1_toy, IUS_12_2_toy, IUS_12_3_toy, 
                     IUS_12_4_toy, IUS_12_5_toy, IUS_12_6_toy,
                     IUS_12_7_toy,IUS_12_8_toy,IUS_12_9_toy,IUS_12_10_toy,
                     IUS_12_11_toy,IUS_12_12_toy)
class(IUS_12_toy)
#> [1] "data.frame"
class(IUS_12_1_toy)
#> [1] "numeric"
library(janitor)
#> 
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#> 
#>     chisq.test, fisher.test
IUS_12_toy %>%
  adorn_totals("col")
#>  IUS_12_1_toy IUS_12_2_toy IUS_12_3_toy IUS_12_4_toy IUS_12_5_toy
#>             2            4            3            4            4
#>             4            5            4            5            4
#>             4            4            4            3            4
#>  IUS_12_6_toy IUS_12_7_toy IUS_12_8_toy IUS_12_9_toy IUS_12_10_toy
#>             2            4            4            3             2
#>             5            5            4            4             3
#>             3            4            4            4             4
#>  IUS_12_11_toy IUS_12_12_toy Total
#>              3             1    34
#>              4             4    47
#>              2             2    38

# The problem is that the sum is wrong, as specified by:

rowSums(IUS_12_toy)
#> [1] 36 51 42

# OK, now I would like to add the results as a new column:

IUS_12_toy[,13] = c("Total", rowSums(IUS_12_toy))

# But I get an error:

#> Error in `[<-.data.frame`(`*tmp*`, , 13, value = c("Total", "36", "51", : replacement has 4 rows, data has 3

reprex package(v0.3.0)创建于2019-09-28

r dataframe
2个回答
0
投票

问题是使用级联'Total'将导致length 1比行数大

IUS_12_toy[,13] <- rowSums(IUS_12_toy)

使用dplyr,我们还可以

library(dplyr)
IUS_12_toy %>%
     mutate(Total = rowSums(.))

或带有purrr

library(purrr)
IUS_12_toy %>%
     mutate(Total = reduce(., `+`))

[此外,如果我们使用索引来创建列,那么默认情况下,data.frame将对make.names/nake.unique进行完整性检查,并附加一个字符作为前缀,即此处为“ V”

我们可以直接使用列名作为字符串

IUS_12_toy["Total"] <- rowSums(IUS_12_toy)

0
投票

运行?adorn_totals,您会在文档的第一句中看到说明:

此函数排除输入data.frame的第一列,假设它是不求和的描述性变量。

哪个占总金额不符合您的期望。

如果行中有一个标识符-我希望行总和有意义,您可以将其添加到第一列中,然后照做。

我在第一列中添加新变量year

library(dplyr)
IUS_12_toy %>%
  mutate(year = 2016:2018) %>%
  select(year, everything()) %>% # move it to the first column position
  adorn_totals("col")

将产生预期的结果。

© www.soinside.com 2019 - 2024. All rights reserved.