将所有行均匀地符合r的条件
我有一个数据框架,例如:
df <- data.frame(col1 = c(1, 2500,1, 1, 1),
col2 = c(12, NA, 8,9, 5),
col3 = c(25, 48, 7, 9, 14))
df
col1 col2 col3
1 1 12 25
2 2500 NA 48
3 1 8 7
4 1 9 9
5 1 5 14
我希望仅当单元格值高于1时,而忽略na值,才能将行总结为这样的数据框架:
df_desired <- data.frame(col1 = c(2500),
col2 = sum(12, 8,9, 5),
col3 = sum(25, 48, 7, 9, 14))
df_desired
col1 col2 col3
1 2500 34 103
我已经走了这么远:
df_test <- df %>%
summarise_at(vars(contains("col")), sum, na.rm = TRUE)
df_test
col1 col2 col3
1 2504 34 103
我've尝试了ifelse
的许多变体,但没有成功。到目前为止,我只发现了跨列的有条件求和并添加新列的示例。
I have a data frame such as:
df <- data.frame(col1 = c(1, 2500,1, 1, 1),
col2 = c(12, NA, 8,9, 5),
col3 = c(25, 48, 7, 9, 14))
df
col1 col2 col3
1 1 12 25
2 2500 NA 48
3 1 8 7
4 1 9 9
5 1 5 14
I am hoping to sum the rows only when cell value is above 1, while ignoring NA values, to make a data frame like this:
df_desired <- data.frame(col1 = c(2500),
col2 = sum(12, 8,9, 5),
col3 = sum(25, 48, 7, 9, 14))
df_desired
col1 col2 col3
1 2500 34 103
I have gotten this far:
df_test <- df %>%
summarise_at(vars(contains("col")), sum, na.rm = TRUE)
df_test
col1 col2 col3
1 2504 34 103
I've tried many variations of ifelse
with no success. I've so far only found examples of conditional summing across columns and adding a new column.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在上使用概述
在中使用 base r 带
colsums
替换
替换 in小于2至na
Using
summarise
withacross
Or in
base R
withcolSums
afterreplace
ing the elements that are less than 2 toNA
我们可以在设置
map_dbl
之后使用Ifelse
语句:或不
Purrr
:We could use
map_dbl
after setting each 1 to 0 within aifelse
statement:Or without
purrr
:在基本中使用
colsums
:in Base R use
colSums
:使用
sapply
函数,您解决问题如下:或使用
汇总
函数Using
sapply
function, you solve your problem as follow:or using
summarise
function