Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.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 - Fatal编程技术网

R函数,该函数合并行并引入新的合并变量

R函数,该函数合并行并引入新的合并变量,r,R,我有一个这样的数据集 ID Brand --- -------- 1 Cokacola 2 Pepsi 3 merge with 1 4 merge with 2 5 merge with 1 6 Fanta 我想写一个R函数,它合并行并根据ID引入新变量,如下所示 ID Brand merge ---- -------- ---

我有一个这样的数据集

ID        Brand
---      --------
1         Cokacola
2         Pepsi
3         merge with 1
4         merge with 2
5         merge with 1
6         Fanta
我想写一个R函数,它合并行并根据ID引入新变量,如下所示

ID          Brand       merge
----       --------   --------
1          Cokacola      1,3,5  
2          Pepsi         2,4   
6          Fanta         6
您的数据:

dat <- data.frame(
    id = 1:6,
    brand = c('Cokacola', 'Pepsi', 'merge with 1', 'merge with 2', 'merge with 1', 'Fanta'))
dat你可以试试

library(reshape2)
indx <- !grepl('merge', df$Brand)
df1 <- df[indx,]
val <- as.numeric(sub('[^0-9]+', '', df[!indx, 'Brand']))
ml <- melt(tapply(which(!indx), val, FUN=toString))
df2 <- merge(df1, ml, by.x='ID', by.y='Var1', all=TRUE)
df2$merge <- with(df2, ifelse(!is.na(value),
               paste(ID, value, sep=', '), ID))
df2[-3]
#   ID    Brand   merge
#1  1 Cokacola 1, 3, 5
#2  2    Pepsi    2, 4
#3  6    Fanta       6
library(重塑2)
indx
library(reshape2)
indx <- !grepl('merge', df$Brand)
df1 <- df[indx,]
val <- as.numeric(sub('[^0-9]+', '', df[!indx, 'Brand']))
ml <- melt(tapply(which(!indx), val, FUN=toString))
df2 <- merge(df1, ml, by.x='ID', by.y='Var1', all=TRUE)
df2$merge <- with(df2, ifelse(!is.na(value),
               paste(ID, value, sep=', '), ID))
df2[-3]
#   ID    Brand   merge
#1  1 Cokacola 1, 3, 5
#2  2    Pepsi    2, 4
#3  6    Fanta       6