替换data.frame中的字符

时间:2018-11-02 13:46:54

标签: r dataframe replace substitution

我有一个data.frame

Client1 Client2 Client3
3        1        9
6        2        19
23       7        20
45       102      101
55       NA       102
61       NA       NA

和另一个具有

的data.frame
number       date 
1        02.11.2018  
2        03.11.2018        
3        04.11.2018        
4        05.11.2018      
...      ....       
102       12.01.2019

这个想法是将第一个data.frame中的高位数字与第二个中的日期相加 并获得:

Client1          Client2             Client3
04.11.2018        04.11.2018         04.11.2018
04.11.2018        04.11.2018         04.11.2018
04.11.2018        04.11.2018         04.11.2018
04.11.2018        04.11.2018         04.11.2018
04.11.2018        NA                 04.11.2018
04.11.2018        NA                 NA

日期不正确,这是一个例子。 谢谢您的帮助:)

3 个答案:

答案 0 :(得分:2)

我们可以使用 match

# example data
df1 <- read.table(text = "Client1 Client2 Client3
3        1        9
6        2        19
23       7        20
45       102      101
55       NA       102
61       NA       NA", header = TRUE)

df2 <- read.table(text = "number       date 
1        02.11.2018  
2        03.11.2018        
3        04.11.2018        
4        05.11.2018      
102       12.01.2019", header = TRUE, stringsAsFactors = FALSE)


# loop through columns, use match
data.frame(lapply(df1, function(i)
  df2$date[ match(i, df2$number) ]
  ))

#      Client1    Client2    Client3
# 1 04.11.2018 02.11.2018       <NA>
# 2       <NA> 03.11.2018       <NA>
# 3       <NA>       <NA>       <NA>
# 4       <NA> 12.01.2019       <NA>
# 5       <NA>       <NA> 12.01.2019
# 6       <NA>       <NA>       <NA>

答案 1 :(得分:1)

假设您的两个数据帧分别称为ClientsDates

library(tidyverse)

Clients %>% 
  gather(everything(), key = Client, value = number) %>% 
  left_join(Dates, by = c("number" = "number")) %>% 
  select(Client, date) %>% 
  spread(key = Client, value = date)

答案 2 :(得分:0)

使用@ zx8754的示例数据,您也可以尝试:

library(qdap)
as.data.frame(apply(df1, 2, lookup, df2))
# output
#     Client1    Client2    Client3
# 1 04.11.2018 02.11.2018       <NA>
# 2       <NA> 03.11.2018       <NA>
# 3       <NA>       <NA>       <NA>
# 4       <NA> 12.01.2019       <NA>
# 5       <NA>       <NA> 12.01.2019
# 6       <NA>       <NA>       <NA>