仍然在学习很多关于R的知识,主要在Stata和SPSS工作。
2部分,相互关联的问题:
1)如何使用数值的第一个数字使R不按字母顺序或数字顺序产生输出?
假设我有一个表示数字信息的因子数据向量(对于这个例子,计数并不重要):
widgets = c("One widget", "Two widgets", "Three widgets", "Four widgets", "Five widgets", "Six widgets", "Seven widgets", "Eight widgets", "Nine widgets", "Ten to Fifteen widgets", "Sixteen or more widgets")
我运行一个基本的表,然后得到:
table(widgets)
widgets
Eight widgets Five widgets Four widgets Nine widgets One widget Zero widgets
1 1 1 1 1 1
但我希望R给我:
table(widgets)
widgets
Zero widgets One widget Four widgets Five widgets Eight widgets Nine widgets
1 1 1 1 1 1
我喜欢使用cbind来使事情更容易阅读,但它会遭受相同的输出排序:
cbind(table(widgets))
[,1]
Eight widgets 1
Five widgets 1
Four widgets 1
Nine widgets 1
One widget 1
Zero widgets 1
2)上面的数据有一个基础数值,我可以使用unclass(小部件)函数看到。那么如何才能将unlass值与我的表格中的字符串标签一起显示?
我的无人问津:
cbind(unclass(widgets))
[,1]
[1,] "Zero widgets"
[2,] "One widget"
[3,] "Four widgets"
[4,] "Five widgets"
[5,] "Eight widgets"
[6,] "Nine widgets"
我想要或类似于此:
cbind(unclass(widgets))
unclass label Freq
1 Zero widgets 1
2 One widget 1
3 Four widgets 1
4 Five widgets 1
5 Eight widgets 1
6 Nine widgets 1
获得最后一张表真的可以帮助我进行重新编码和其他工作。谢谢!
将widget
编码为factor
以获得所需的结果。
# make widgets
# a factor class
widgets <-
factor(
x = c("One widget"
, "Two widgets"
, "Three widgets"
, "Four widgets"
, "Five widgets"
, "Six widgets"
, "Seven widgets"
, "Eight widgets"
, "Nine widgets"
, "Ten to Fifteen widgets"
, "Sixteen or more widgets"
)
, levels = c("One widget"
, "Two widgets"
, "Three widgets"
, "Four widgets"
, "Five widgets"
, "Six widgets"
, "Seven widgets"
, "Eight widgets"
, "Nine widgets"
, "Ten to Fifteen widgets"
, "Sixteen or more widgets"
)
)
# view table output
table( widgets )
# widgets
# One widget Two widgets
# 1 1
# Three widgets Four widgets
# 1 1
# Five widgets Six widgets
# 1 1
# Seven widgets Eight widgets
# 1 1
# Nine widgets Ten to Fifteen widgets
# 1 1
# Sixteen or more widgets
# 1
# transform widgets
# count into data frame
widgets.count <-
data.frame(
table( widgets )
)
# view data frame
widgets.count
# widgets Freq
# 1 One widget 1
# 2 Two widgets 1
# 3 Three widgets 1
# 4 Four widgets 1
# 5 Five widgets 1
# 6 Six widgets 1
# 7 Seven widgets 1
# 8 Eight widgets 1
# 9 Nine widgets 1
# 10 Ten to Fifteen widgets 1
# 11 Sixteen or more widgets 1
# end of script #