Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将列拆分为两个相应的数据帧值_R_Dplyr - Fatal编程技术网

R 将列拆分为两个相应的数据帧值

R 将列拆分为两个相应的数据帧值,r,dplyr,R,Dplyr,我有一个数据帧,如: library(tidyverse) tib <- tibble(Dis = c("One", "One", "Two", "Three", "Three"), Spray = c("F1", "F1", "F2", "other", "nj"

我有一个数据帧,如:

library(tidyverse)

tib <- tibble(Dis = c("One", "One", "Two", "Three", "Three"),
             Spray = c("F1", "F1", "F2", "other", "nj"),
             freq= c(80, 20, 1.34, 15.3, 20.2),
             Nom = c("A", "B", "C", "C", "D") )
库(tidyverse)

tib我看不到分割列的方法,但是您可以使用
left\u join()
mutate()
的组合来实现所需的输出

库(tidyverse)
tib%>%
左连接(fs,by=c(“喷洒”=“s”))
#>#tibble:5 x 5
#>喷射频率
#>       
#>1一个F1 80 A
#>2一个F1 20 B
#>3两个F2 1.34 C
#>4其他三个15.3 C F1
#>5三个nj 20.2 D F2
tib%>%
左连接(fs,by=c(“Spray”=“s”))%>%
左连接(fs,by=c(“Spray”=“f”))
#>#tibble:5 x 6
#>喷射频率
#>        
#>1一个F1 80另一个
#>2一个F1 20 B另一个
#>3两个F2 1.34 C nj
#>4其他三个15.3 C F1
#>5三个nj 20.2 D F2
#所需输出
tib%>%
左连接(fs,by=c(“Spray”=“s”))%>%
左连接(fs,by=c(“Spray”=“f”))%>%
变异(f=如果其他(是na(f),喷洒,f),
s=如果有其他情况(即:na(s),喷洒,s))
#>#tibble:5 x 6
#>喷射频率
#>        
#>1一个F1 80另一个F1 80
#>2一个F1 20 B F1另一个
#>3两个F2 1.34 C F2 nj
#>4其他三个15.3 C F1其他
#>5三个nj 20.2 D F2 nj
是由(v0.3.0)于2021-03-08年创建的?(我认为你的预期产出在第5行,如果不是,我不知道你在寻找什么:p)


tib$f我看不到
tib
ans
fs
数据帧之间的公共值。
tib
中的哪列应与
fs
中的哪列相对应?我也不知道
Spray
列如何在所需输出中拆分为两列。这可能会让我感到困惑,但我需要一种逻辑方法来处理如何从输入到所需输出。你能再解释一下吗?例如,为什么输出中的
Spray
s
中获取(我似乎是随机的)值?@Wimpel:对不起,前面的尝试中有输入错误,我更正了使用mutate时最后一段代码中的posit shows错误<代码>错误:
mutate()`input
f
有问题。x
false
必须是字符向量,而不是
因子
对象。ℹ 输入
f
is
if_-else(is.na(f),Spray,f)
`在
if_-else()中
将最后一个参数从
f
更改为
as.character(f)
s
列可能也需要它。
f <- c("F1", "F2", "F3", "F4", "F5", "F6", "F7")
s <- c("other", "nj", "na", "ker", "dsf", "dsf", "rth")

fs <- data.frame(f, s)
Dis   Spray  freq  Nom    f     s 
<chr> <chr> <dbl> <chr> <chr> <chr>
1 One   F1    80    A    F1    other
2 One   F1    20    B    F1    other
3 Two   F2    1.34  C    F2    nj
4 Three other 15.3  C    F1    other
5 Three nj    20.2  D    F2    other
tib$f <- NA
tib$s <- NA
c <- 1

for (i in tib$Spray){
  if (i %in% f){
    tib$f[c] <- i
    is <- match(i,f)
    tib$s[c] <- s[is]
    c <- c + 1
  }
  else{
    is <- match(i,s)
    tib$f[c] <- f[is]
    tib$s[c] <- i
    c <- c + 1
  }
}