我想通过重复观察来转换长数据集:
obs code
1 A
2 B
4 G
2 D
1 H
3 K
使用逗号分隔的摘要列进入“更短”的数据集:
obs code
1 A,H
2 B,D
3 K
4 G
我尝试过类似的事情:
df <- data.frame(obs=c("1","2","4","2","1","3"), code=c("A","B","G","D","H","K"),stringsAsFactors = F)
df %>% group_by(obs) %>%
mutate(id=1:n()) %>%
spread(id,code) %>%
replace_na(list(`1` = "", `2` = "")) %>%
unite(new,2:3, remove=FALSE,sep=",")
但是,对于3号和4号,这给了我额外的“,”。 有没有更好的解决我的问题?
答案 0 :(得分:3)
而不是spread
采用'宽'格式,然后使用replace_na
,这可以通过paste
summarise
之后的group_by
更直接地完成df %>%
group_by(obs) %>%
summarise(code = toString(code))
步骤
let data = new FormData();
data.append('file', this.avatar);
data.append('_method', 'put'); // add this
axios.post('/api/user/updateAvatar',data) // change this to post )
.then(res =>{
console.log(res);
})
.catch(error => console.log(error)); //
window.location.href = "/profile";
}
答案 1 :(得分:1)
以下是使用aggregate
替代的基础R解决方案:
with(df, aggregate(code, by = list(obs = obs), toString));
# obs x
#1 1 A, H
#2 2 B, D
#3 3 K
#4 4 G
如果您不希望在code
之间留出额外空间,则可以paste0
条目(而非使用toString
):
with(df, aggregate(code, by = list(obs = obs), paste0, collapse = ","));
# obs x
#1 1 A,H
#2 2 B,D
#3 3 K
#4 4 G