使用dplyr函数迭代字符向量中的值
我有几个变量(使用dplyr函数迭代字符向量中的值,r,for-loop,dplyr,tibble,R,For Loop,Dplyr,Tibble,我有几个变量(id.type和id.subtype,在本例中),我想使用dplyr包检查tibleall.snags中的不同值。我希望将它们分类,并在控制台中打印出所有值(TIBLE通常只打印前10个)。输出将等效于以下代码: distinct(all.snags,id.type) %>% arrange(id.type) %>% print(n = Inf) distinct(all.snags,id.subtype) %>% arrange(id.subtype) %&g
id.type
和id.subtype
,在本例中),我想使用dplyr
包检查tibleall.snags
中的不同值。我希望将它们分类,并在控制台中打印出所有值(TIBLE通常只打印前10个)。输出将等效于以下代码:
distinct(all.snags,id.type) %>% arrange(id.type) %>% print(n = Inf)
distinct(all.snags,id.subtype) %>% arrange(id.subtype) %>% print(n = Inf)
我认为通过循环向量中的值可以更好地实现这一点,但我无法让它工作
distinct.vars <- c("id.type","id.subtype")
for (i in distinct.vars) {
distinct(all.snags,distinct.vars[i]) %>%
arrange(distinct.vars[i]) %>%
print(n = Inf)
}
distinct.vars%
排列(不同的.vars[i])%>%
打印(n=Inf)
}
我认为这个功能正是您想要的:
library(dplyr)
df = iris
print_distinct = function(df, columns) {
for (c in columns) {
print(df %>% distinct_(c) %>% arrange_(c))
}
}
print_distinct(df, c("Sepal.Length", "Sepal.Width"))
我不明白。你写的前两行代码似乎做了你想做的事情,那么问题是什么?如果代码只写一次,并且可以向现有的字符向量添加额外的变量,那么它的可伸缩性就更大了。听起来你想要一个函数吗?这很有效,除了我想单独查看每一列,而不是一起查看。