【发布时间】:2021-06-30 02:40:26
【问题描述】:
我正在尝试删除单个列,但我不能。
对于上下文,我正在尝试使用以下格式的数据计算某些汇总统计数据:
State Year G1.Institutions
Alabama-1935 Alabama 1935 NA
Alabama-1936 Alabama 1936 0.4830918
Alabama-1937 Alabama 1937 0.0000000
Alabama-1938 Alabama 1938 0.0000000
Alabama-1939 Alabama 1939 0.4807692
Alabama-1940 Alabama 1940 0.0000000
根据上面的数据,我使用以下方法构建新表:
descriptives<-aggregate(G1.Institutions~ State, grow_us, mean)
descriptives$sd<-aggregate(G1.Institutions ~ State, grow_us, sd)
y1935 <-panel_data[panel_data$Year %in% c(1935 ), ]
y2019 <-panel_data[panel_data$Year %in% c(2019 ), ]
descriptives$y1935<-y1935$Institutions
descriptives$y2019<-y2019$Institutions
descriptives$change<-descriptives$y2019-descriptives$y1935
descriptives
然后给我以下输出:
State G1.Institutions sd.State sd.G1.Institutions y1935 y2019 change
1 Alabama -0.7513443 Alabama 2.868676 207 106 -101
2 Alaska 1.5304305 Alaska 11.986212 2 4 2
3 Arizona 0.6237702 Arizona 11.817228 15 14 -1
4 Arkansas -1.0421333 Arkansas 2.492121 213 86 -127
5 California -0.4250102 California 7.484268 245 137 -108
6 Colorado -0.7262110 Colorado 5.486192 141 67 -74
这里的问题是聚合函数创建列 sd.State 是多余的,我想摆脱它。这就是麻烦开始的地方,这通常应该很容易操作,但事实并非如此。我尝试使用以下方法删除该列:
descriptives = subset(descriptives, select = -c(3) )
这去掉了第 3 列,但有趣的是它使用了第 4 列,现在数据看起来像这样:
State G1.Institutions y1935 y2019 change
1 Alabama -0.7513443 207 106 -101
2 Alaska 1.5304305 2 4 2
3 Arizona 0.6237702 15 14 -1
4 Arkansas -1.0421333 213 86 -127
我还尝试了一些其他常用的删除列的方法,例如:
descriptives = descriptives[,!(names(descriptives) %in% 'sd.State')]
有趣的是,代码运行没有错误但没有效果:
State G1.Institutions sd.State sd.G1.Institutions y1935 y2019 change
1 Alabama -0.7513443 Alabama 2.868676 207 106 -101
2 Alaska 1.5304305 Alaska 11.986212 2 4 2
3 Arizona 0.6237702 Arizona 11.817228 15 14 -1
4 Arkansas -1.0421333 Arkansas 2.492121 213 86 -127
我进一步尝试:
descriptives$sd.State <- NULL
但由于某种原因,将整个数据框设置为 null 而不仅仅是那一列。
无论我尝试什么,我都无法仅删除 sd.State 列而不删除 sd.G1.Institutions 列。他们似乎以某种方式联系在一起。我认为这与聚合函数有关,因为我只是在使用它时遇到了这个问题。
我试图搜索过去的答案以寻找可能的解决方案,但我什至不知道这里的问题是什么。出于某种原因,关于删除列的问题的答案在这里根本不起作用。
【问题讨论】: