为什么在使用transform()创建新列时会得到一堆额外的列?

ie3xauqp  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(93)

我试图在R中创建一个变量v2elboycot_ord的一年滞后版本。如果发生抵制,则该变量取值为1,否则取值为0。下面是我用来做这件事的代码:

subset$Lagged_boycott<-transform(subset,Lagged_boycott=c(v2elboycot_ord[-1],NA))

这给了我一个df,它有很多额外的列,我做错了什么?

structure(list(COWcode = c(70L, 70L, 70L, 70L, 70L, 70L), country_name = c("Mexico", 
"Mexico", "Mexico", "Mexico", "Mexico", "Mexico"), year = c(1946L, 
1949L, 1952L, 1955L, 1958L, 1961L), v2x_regime = c(1L, 1L, 1L, 
1L, 1L, 1L), v2elboycot_ord = c(1, 1, 1, 1, 1, 0), v2xel_elecparl = c(1L, 
1L, 1L, 1L, 1L, 1L), v2elintim_ord = c(1L, 1L, 1L, 2L, 2L, 2L
), v2xel_frefair = c(0.062, 0.081, 0.086, 0.091, 0.096, 0.098
), v2xnp_regcorr = c(0.858, 0.858, 0.858, 0.858, 0.858, 0.858
), v2lgcrrpt_ord = c(1, 1, 1, 1, 1, 1), v2lgfunds_ord = c(1L, 
1L, 1L, 1L, 1L, 1L), v2lgcomslo_ord = c(2L, 2L, 2L, 2L, 2L, 2L
), e_gdppc = c(3.174, 3.568, 4.288, 4.644, 5.121, 5.526)), row.names = c(NA, 
6L), class = "data.frame")
uxhixvfz

uxhixvfz1#

问题是您混合了两个接口,而这两个接口并不应该被使用。transform()返回的是整个数据集以及修改过的列,因此您应该将其赋给数据集名称,而不是该数据集的列。例如,

subset <- transform(subset, Lagged_boycott = c(v2elboycot_ord[-1], NA))

或者,如果您想给列赋值,不要使用transform();或者索引到subset...

subset$Lagged_boycott <- c(subset$v2elboycot_ord[-1], NA)

...或使用with()

subset$Lagged_boycott <- with(subset, c(v2elboycot_ord[-1], NA))

所有这些方法的结果:

#> subset[c("v2elboycot_ord", "Lagged_boycott")]
  v2elboycot_ord Lagged_boycott
1              1              1
2              1              1
3              1              1
4              1              1
5              1              0
6              0             NA

相关问题