r - 如何对r中的几列求和?

我想对数据框中的几列求和。 例如,使用 iris r-base

例如,我想对 Sepal.Length、Petal.Length 和 Petal.Width 列进行求和

我尝试了colSums,但没有成功。

 df<-iris%>%
  select(-Species)%>%
  colSums([1:4])

更新:我尝试修改问题以使其更贴近我的现实。

最佳答案

我想你想做

colSums(iris[1:4])

iris[1:4] %>% colSums()

使用 %>% 管道的其他选项是

iris %>% 
  select(Sepal.Length,  Sepal.Width, Petal.Length,  Petal.Width) %>% 
  colSums()

或使用新的across函数

iris %>% 
  summarise(across(1:4, sum))

更详细的选项,但我喜欢在添加最小、最大四分位数等时使用它

iris %>% 
  summarise(Sepal.Length = sum(Sepal.Length),  
            Sepal.Width  = sum(Sepal.Width), 
            Petal.Length = sum(Petal.Length),  
            Petal.Width  = sum(Petal.Width))

https://stackoverflow.com/questions/68037949/

相关文章:

reactjs - 难以创建基本线(@react-three/fiber 和 Typescript)

c++ - 为什么默认参数在模板函数中不起作用?

javascript - Next JS 和 Cloudinary,图像未加载

delphi - Spring4D TDistinctIterator.ToArra

kotlin - 如何在 Kotlin Exposed 中获取插入的行?

java - 设置标题背景 Vaadin 14 网格

flutter - 如何将二进制字符串转换为文本字符串并在 flutter 中反转?

flutter - Flutter 中 colorScheme 和 ThemeData 声明的原色

react-native - SectionList React Native 上的粘性 heade

c++ - 无法将 'v8::MaybeLocal' 转换为 'v8::Lo