相当于SQL更新查询

时间:2021-09-15 00:01:20

I want to do the equivalent of an UPDATE query in SQL using R. If I have data like this:

如果我有这样的数据:

# Example Data
df <- data.frame(x <- c("My Name", "My Name"), y <- c("AZ", "MI"))
colnames(df) <- c("Name", "State")

print(df)

> print(df)
     Name State
1 My Name    AZ
2 My Name    MI

I'd like to do the R equivalent of this in SQL :

我想用SQL中的R来表示:

update df
set Name = 'My Name1' 
where Name = 'My Name' 
and State = 'MI

So the final output is:

所以最终输出是:

> print(df)
      Name State
1  My Name    AZ
2 My Name1    MI

Any ideas?

什么好主意吗?

2 个解决方案

#1


3  

Because you're using factors in your data frame, you are going to need to change the factor levels first using

因为你在数据框中使用因子,你需要首先改变因子水平

levels(df$Name) <- c(levels(df$Name), "My Name1")

before actually changing the data frame using

在实际使用数据帧之前

df[df$Name == "My Name" & df$State == "MI", "Name"] <- "My Name1"

#2


0  

The syntax is:

的语法是:

df[logical condition OR rownumbers, column name or number] <- assignment

df[逻辑条件或行号,列名或数字]<-赋值

So you could do:

所以你可以做的:

df[df$Name == "MyName" & df$State == "MI", "State"] <- "My Name1"

#1


3  

Because you're using factors in your data frame, you are going to need to change the factor levels first using

因为你在数据框中使用因子,你需要首先改变因子水平

levels(df$Name) <- c(levels(df$Name), "My Name1")

before actually changing the data frame using

在实际使用数据帧之前

df[df$Name == "My Name" & df$State == "MI", "Name"] <- "My Name1"

#2


0  

The syntax is:

的语法是:

df[logical condition OR rownumbers, column name or number] <- assignment

df[逻辑条件或行号,列名或数字]<-赋值

So you could do:

所以你可以做的:

df[df$Name == "MyName" & df$State == "MI", "State"] <- "My Name1"