一个例子:
a = c(10,20,30)
b = c(1,2,3)
c = c(4,5,6)
d = c(7,8,9)
df=data.frame(a,b,c,d)
library(dplyr)
df_1 = df %>% mutate(a1=sum(a+1))
Run Code Online (Sandbox Code Playgroud)
如何在“ a”(或任何其他定义的位置)之后而不是末尾添加“ a1”?
谢谢。
# Sample dataframe
set.seed(123)
d = data.frame(x = runif(120), grp = gl(3, 40))
# Select top_n
d %>%
group_by(grp) %>%
top_n(n=3, wt=x)
Run Code Online (Sandbox Code Playgroud)
如何在同一管道内同时选择顶部和底部观测值?已尝试以下但不起作用
# helper function
my_top_bott = function(x, n, wt) {
x1 = x %>% top_n(n=n, wt=wt)
x2 = x %>% top_n(n=n, wt=-wt)
x = bind_rows(x1, x2)
return(x)
}
# Pipe
d %>%
group_by(grp) %>%
my_top_bott(., n=3, wt=x)
Run Code Online (Sandbox Code Playgroud) 一个数据框:
a = c("a", "", "c", "", "e")
b = c(1, 2, 3, 4, 5)
c = c("g", "h", "i", "j", "k")
df = data.frame(a,b,c)
Run Code Online (Sandbox Code Playgroud)
当“a”为空时,如何使用 dplyr 用“c”列中的相应值填充“a”列。我知道如何使用 data.table 做到这一点。
谢谢你。