我试图从SPSS转换为R;我想将我的清理语法翻译为学习R的好方法,但是我在SPSS中的简单命令遇到了很多麻烦。
以下代码适用于SPSS:
IF (n_race = 1 & (n_ethnicity = 7 | n_ethnicity = 8 | n_ethnicity = 99)) race_eth=1.
EXECUTE.
IF (n_ethnicity = 3 & (n_race = 1 | n_race = 99)) race_eth=2.
EXECUTE.
IF (n_race = 2) race_eth=3.
EXECUTE.
IF (n_race = 5 & n_ethnicity NE 9) race_eth=4.
EXECUTE.
IF ((n_ethnicity = 2 | n_ethnicity = 4 | n_ethnicity = 5) & (n_race = 1 | n_race = 99)) race_eth=4.
EXECUTE.
IF (n_ethnicity = 9 & (n_race = 1 | n_race = 5 | n_race = 99)) race_eth=5.
EXECUTE.
IF (n_race = 4 | (n_ethnicity = 6 & (n_race = 1 | n_race = 99))) race_eth=6.
EXECUTE.
IF (n_ethnicity = 1 & (n_race = 1 | n_race = 99)) race_eth=6.
EXECUTE.
IF (n_race=99 AND (n_ethnicity=7 OR n_ethnicity=99 OR n_ethnicity=8)) race_eth=99.
EXECUTE.
我认为这段代码会在R中做同样的事情,但是单元格频率不一样(注意我在n中将n_ethnicity重命名为n_ethity)。我非常感谢任何帮助!谢谢!
OMSOct14_Mar16$race_eth[n_race == 1 & (n_eth == 7 | n_eth == 8 | n_eth == 99)] <- 1
OMSOct14_Mar16$race_eth[n_eth == 3 & (n_race == 1 | n_race == 99)] <- 2
OMSOct14_Mar16$race_eth[n_race == 2] <- 3
OMSOct14_Mar16$race_eth[n_race == 5 & n_eth != 9] <- 4
OMSOct14_Mar16$race_eth[(n_eth == 2 | n_eth==4 | n_eth==5) & (n_race == 1 | n_race == 99)] <- 4
OMSOct14_Mar16$race_eth[n_eth == 9 & (n_race == 1 | n_race == 5 | n_race==99)] <- 5
OMSOct14_Mar16$race_eth[n_race == 4 | (n_eth == 6 & (n_race==1 | n_race == 99))] <- 6
OMSOct14_Mar16$race_eth[n_eth == 1 & (n_race == 1 | n_race == 99)] <- 6
OMSOct14_Mar16$race_eth[n_race == 99 & (n_eth == 7 | n_eth == 8 | n_eth==99)] <- 99
答案 0 :(得分:1)
您可以使用with
和ifelse
执行此类操作:
set.seed(99)
n_race<-c(1,99,2,5,4)
n_eth<-c(7,8,99,3,9,2,4,5,6,1)
OMSOct14_Mar16<-data.frame(n_race = sample(n_race, 20, replace = T),
n_eth = sample(n_eth, 20, replace = T))
OMSOct14_Mar16$race_eth<-
with(OMSOct14_Mar16,ifelse(n_eth == 1 & n_eth %in% c(7,8,99), 1,
ifelse(n_eth == 3 & n_race %in% c(1,99), 2,
ifelse(n_race == 2, 3,
ifelse(n_race==5 & n_eth !=9, 4,
ifelse(n_eth %in% c(2,4,5) & n_race %in% c(1,99), 4,
ifelse(n_eth == 9 & n_race %in% c(1,5,99), 5,
ifelse(n_race ==4 | n_eth == 6 & (n_race %in% c(1,99)), 6,
ifelse(n_eth == 1 & n_race %in% c(1,99), 6,
ifelse(n_race == 99 & (n_eth %in% c(7,8)), 99, NA))))))))))
head(OMSOct14_Mar16,5)
n_race n_eth race_eth
2 99 3
1 7 NA
5 6 4
4 2 6
2 5 3