如何避免在R中多次写入同一行?

时间:2014-04-10 16:40:41

标签: r dataset

我在R中编写程序,我需要根据变量之一的特定值选择变量。该计划是下一个:

a1961 <- base[base[,5]==1961,]
a1962 <- base[base[,5]==1962,]
a1963 <- base[base[,5]==1963,]
a1964 <- base[base[,5]==1964,]
a1965 <- base[base[,5]==1965,]
a1966 <- base[base[,5]==1966,]
a1967 <- base[base[,5]==1967,]
a1968 <- base[base[,5]==1968,]
a1969 <- base[base[,5]==1969,]
a1970 <- base[base[,5]==1970,]
a1971 <- base[base[,5]==1971,]
a1972 <- base[base[,5]==1972,]
a1973 <- base[base[,5]==1973,]
a1974 <- base[base[,5]==1974,]
a1975 <- base[base[,5]==1975,]
a1976 <- base[base[,5]==1976,]
a1977 <- base[base[,5]==1977,]
a1978 <- base[base[,5]==1978,]
a1979 <- base[base[,5]==1979,]
a1980 <- base[base[,5]==1980,]
a1981 <- base[base[,5]==1981,]
a1982 <- base[base[,5]==1982,]
a1983 <- base[base[,5]==1983,]
a1984 <- base[base[,5]==1984,]
a1985 <- base[base[,5]==1985,]
a1986 <- base[base[,5]==1986,]
a1987 <- base[base[,5]==1987,]
a1988 <- base[base[,5]==1988,]
a1989 <- base[base[,5]==1989,]
...
a2012 <- base[base[,5]==2012,]

有没有办法(比如SAS中的模块)我可以避免一遍又一遍地写同样的东西?

2 个答案:

答案 0 :(得分:6)

通常,编码/实现问题确实属于StackOverflow。也就是说,我的建议不是为每个结果命名单个变量,而是将它们全部放入列表中:

a = lapply(1961:1989, function(x) base[base[,5]==x,]

答案 1 :(得分:3)

您还可以使用assign command

years <- 1961:2012
for(i in 1:length(years)) {
  assign(x = paste0("a", years[i]), value = base[base[,5]==years[i],])
}