rowSums将列追加到数据集[已关闭]

nafvub8i  于 2023-05-11  发布在  其他
关注(0)|答案(2)|浏览(140)

**关闭。**这个问题是not reproducible or was caused by typos。目前不接受答复。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
6天前关闭。
Improve this question
我试图通过函数rowSums传递一个列向量并附加到 Dataframe (data)来附加一列rowSums。

data <- cbind(data, rowSums=rowSums(data[,c("serv_1", "serv_2", "serv_3")]))                                                  

#Data looks like this
    serv_1  serv_2 serv_3    
obs_1  0        1     1       
obs_2  1        1     0       
obs_3  0        0     1       
obs_4  0        1     0

我收到一条错误信息

Error in h(simpleError(msg, call)) : 
T  error in evaluating the argument 'x' in selecting a method for function 'rowSums': undefined columns selected

所需的输出如下所示:

serv_1  serv_2 serv_3 rowSums   
obs_1  0        1     1       1
obs_2  1        1     0       2
obs_3  0        0     1       0
obs_4  0        1     0       1

这是否与将列追加到数据框有关?解决办法是什么?
这就是变量是如何用快速虚拟模型创建的

library(fastDummies)
   DUMMY_COL_VARS = c("serv_1", "serv_2", "serv_3")
   data <- dummy_cols(data, select_columns = DUMMY_COL_VARS)
qyyhg6bp

qyyhg6bp1#

tidyverse解决方案:

library(dplyr)
data <- data %>% 
    mutate(
        rowSums = rowSums(across(contains('serv')))
    )

在其中一个包示例上运行我的代码工作正常:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data.frame(city = c("SF", "SF", "NYC"),
           year = c(1990, 2000, 1990),
           crime = 1:3) %>% 
    fastDummies::dummy_cols() %>% 
    mutate(
        rs = rowSums(across(contains('city_')))
    )
#>   city year crime city_NYC city_SF rs
#> 1   SF 1990     1        0       1  1
#> 2   SF 2000     2        0       1  1
#> 3  NYC 1990     3        1       0  1

创建于2023-05-04使用reprex v2.0.2

k2arahey

k2arahey2#

用R碱基

df$rowSums <- rowSums(df[,c("serv_1","serv_2","serv_3")])

输出

serv_1 serv_2 serv_3 rowSums
obs_1      0      1      1       2
obs_2      1      1      0       2
obs_3      0      0      1       1
obs_4      0      1      0       1

相关问题