我在R中计数时遇到了问题。每个变量的拼写略有不同,如下所示
df<-data.frame(sweets= c("cookie", "CANDY", "Cookie", "cake", "IceCream", "Candy", "Chocolate", "COOKIE", "CAKE"))
df
我希望能够这样做。要做到这一点,我希望更改每个变量名以保持一致
df2<-data.frame(sweets= c("Cookie", "Candy", "Cookie", "Cake", "IceCream", "Candy", "Chocolate", "Cookie", "Cake"))
df3<- table(df2)
我用了if_else或者if...if else函数,但是很混乱。如果你能写一个示例代码来说明怎么做,那就太好了。
2条答案
按热度按时间xienkqul1#
在
mutate
中使用stringr
中的str_to_title
,你可以 "convert case" 你的变量,然后你可以使用count
来计算每个甜点的观察次数。代码
输出
zbsbpyhn2#
全部转换为小写,然后转换为 table:
或者
?tolower
提供了一个辅助函数- capwords: