簡體   English   中英

根據條件將值分配給另一列中的一列

[英]Assign value to a column from another column based on condition

說我有一個這樣的清單:

> desired <- c("10001", "10004")

還有一個示例數據框,如下所示:

> desired_sample_df <- data.frame(geo = rep("other", 30), zip = c(rep(10001:10010, 2), 10011:10020), cbsa = c(rep("NY", 20), rep("CA", 10)))
> desired_sample_df
     geo   zip cbsa
1  other 10001   NY
2  other 10002   NY
3  other 10003   NY
4  other 10004   NY
5  other 10005   NY
6  other 10006   NY
7  other 10007   NY
8  other 10008   NY
9  other 10009   NY
10 other 10010   NY
11 other 10001   NY
12 other 10002   NY
13 other 10003   NY
14 other 10004   NY
15 other 10005   NY
16 other 10006   NY
17 other 10007   NY
18 other 10008   NY
19 other 10009   NY
20 other 10010   NY
21 other 10011   CA
22 other 10012   CA
23 other 10013   CA
24 other 10014   CA
25 other 10015   CA
26 other 10016   CA
27 other 10017   CA
28 other 10018   CA
29 other 10019   CA
30 other 10020   CA

僅當zip的值在開始時保存的desired列表中時,我才想用zip的值覆蓋geo列。


這是我嘗試過的:

> desired_sample_df$geo[desired_sample_df$zip %in% desired] <- desired_sample_df$zip[which(desired_sample_df$zip %in% desired)]
Warning message:
In `[<-.factor`(`*tmp*`, desired_sample_df$zip %in% desired, value = c(NA,  :
  invalid factor level, NA generated


> desired_sample_df$geo[desired_sample_df$zip %in% desired] <- desired_sample_df$zip
Warning messages:
1: In `[<-.factor`(`*tmp*`, desired_sample_df$zip %in% desired, value = c(NA,  :
  invalid factor level, NA generated
2: In `[<-.factor`(`*tmp*`, desired_sample_df$zip %in% desired, value = c(NA,  :
  number of items to replace is not a multiple of replacement length

問題之一是數據幀中的字符串會自動成為因素。 嘗試這個:

desired <- c("10001", "10004")
df <- data.frame(geo = rep("other", 30), zip = c(rep(10001:10010, 2), 10011:10020), cbsa = c(rep("NY", 20), rep("CA", 10)), stringsAsFactors=FALSE)

idx <- df$zip %in% desired

現在,您可以通過以下方式更改所需的元素

df[idx, ]$geo <- df[idx, ]$zip

像這樣?

df$geo <- ifelse(df$zip %in% desired,df$zip,df$geo)

在這里我叫你的desired_sample_df ,只是df

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM