更新数据框的子集 [英] Updating a subset of a dataframe

查看:58
本文介绍了更新数据框的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个数据框

col.1 <- c("a", "b", "c", "d", "e", "b", "c")
col.2 <- c(22, 33, 55, 66, 66, 22, 54)
df <- data.frame(col.1, col.2)

,我想更新 col.2 到100,当 df $ col.1 search.df

and I would like to update col.2 to 100 when the df$col.1 matches the search.df

search.df <- c("b", "d")

实际上我有 dataframe 超过1k行,而我的 search.df 有16个元素。我知道一些SQL,但在R中找不到直接的更新。

In fact I have dataframe of 1k+ rows and my search.df has 16 elements. I know some SQL and I can't find a straightforward update in R.

推荐答案

df[df[,1] %in% search.df, 2] <- 100

或如果要直接使用数据框的列元素

or if you want to use column elements of the data frame directly

df$col.2[df$col.1 %in% search.df] <- 100

为简单起见,相同的细分项:

For simplicity, the same broken down:

# get index of rows to be updated by checking each value 
# in col1 against search.df => e.g. FALSE, TRUE, FALSE, ...
index <- df[,1] %in% search.df

# update col2 where index is TRUE to a new value
df[index, 2] <- 100

这篇关于更新数据框的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆