在R中:如何根据现有变量的条件创建新变量

时间:2015-03-05 17:10:23

标签: r

在R中,我想基于我对现有变量(var1和var2)应用的条件创建两个新变量(var3和var4),这些变量具有重复记录。这是我的数据的样子。

Var1  var2  
01     A
01     B
01     A
02     C
02     C
03     D
04     E
04     D
04     F
.      .
.      .
.      .
.      .
.      .

我会在SAS中使用以下if-else-then语句。

if var1 = 01 and var2 = "A" then do; var3 = "New York"; var4= "Buffalo"; end; else;
if var1 = 01 and var2 = "B" then do; var3 = "New York"; var4= "Cornell"; end; else;
if var1 = 02 and var2 = "C" then do; var3 = "North Carolina"; var4= "Raleigh"; end; else;
if var1 = 03 and var = "D"then do; var3 = "Texas"; var4= "Dallas"; end; else;

我的输出将如下所示

Var1  var2    var3             var4
01     A      New York         Buffalo
01     B      New York         Cornell
01     A      New York         Buffalo
02     C      North Carolina   Raleigh
02     C      North Carolina   Raleigh
03     D      Texas            Dallas
.      .      .                 .
.      .      .                 . 
.      .      .                 .
.      .      .                 .    

非常感谢在R中创建上述输出的任何帮助。我是否需要使用if-else和for statement,ifelse等?

2 个答案:

答案 0 :(得分:3)

df$var3<-ifelse(Var1==01, "New York",
         ifelse(Var1==02, "North Carolina",
         ifelse(Var1==03, "Texas", NA)))
df$var4<-....

或者通过申请标签:

df$var3<-factor(df$Var1,
                levels = 1:3,
                labels = c("New York","North Carolina","Texas"))

答案 1 :(得分:0)

您可以创建索引数据集(&#39; df2&#39;)并将其与原始数据集合并(&#39; df1&#39;)

 merge(df1, df2)
 #  var1 var2           var3    var4
 #1   01    A       New York Buffalo
 #2   01    A       New York Buffalo
 #3   01    B       New York Cornell
 #4   02    C North Carolina Raleigh
 #5   02    C North Carolina Raleigh
 #6   03    D          Texas  Dallas

数据

df1 <- structure(list(var1 = c("01", "01", "01", "02", "02", "03"), 
var2 = c("A", "B", "A", "C", "C", "D")), .Names = c("var1", 
"var2"), row.names = c(NA, -6L), class = "data.frame")

df2 <-  data.frame(var1=c('01', '01', '02', '03'), var2=LETTERS[1:4], 
 var3=c('New York', 'New York', 'North Carolina', 'Texas'),
 var4=c('Buffalo', 'Cornell', 'Raleigh', 'Dallas'))