I need to merge two tables in R.
The table X looks this way:
company_name country_code country cost1 cost2
1 Test1 FR <NA> NA 9.945000e-02
2 Test1 BR Brazil NA NA
3 Test2 <NA> USA 1 1.053000e-01
The table Y looks this way:
country country_code tier
France FR 1
Brazil BR 2
USA US 1
I need to merge X and Y to get Z:
name country_code tier
Test1 FR 1
Test2 BR 2
....
What should I do to merge by OR condition or something?
The following will do it. Note that I use a function from package zoo, so you will need to have it installed.
m <- merge(df1, df2, all = TRUE)
m$country <- zoo::na.locf(m$country)
m <- lapply(split(m, m$country), function(.m) zoo::na.locf(.m, fromLast = TRUE))
m <- lapply(m, function(.m) zoo::na.locf(.m))
m <- do.call(rbind, m)
m <- m[!duplicated(m), c(3, 2, 4)]
row.names(m) <- NULL
m
# name country_code tier
#1 First FR 1
#2 Third US 1
#3 Second BR 2
DATA.
df1 <-
structure(list(name = structure(1:3, .Label = c("First", "Second",
"Third"), class = "factor"), country = structure(c(1L, NA, 2L
), .Label = c("France", "USA"), class = "factor"), country_code = structure(c(NA,
1L, 2L), .Label = c("BR", "US"), class = "factor")), .Names = c("name",
"country", "country_code"), class = "data.frame", row.names = c(NA,
-3L))
df2 <-
structure(list(country = structure(c(2L, 1L, 3L), .Label = c("Brazil",
"France", "USA"), class = "factor"), country_code = structure(c(2L,
1L, 3L), .Label = c("BR", "FR", "US"), class = "factor"), tier = c(1L,
2L, 1L)), .Names = c("country", "country_code", "tier"), class = "data.frame", row.names = c(NA,
-3L))
EDIT.
After the comments and the question edit by the OP, the input data has changed and the following code and new df1 reflect that change.
fun <- function(DF, col){
sp <- split(DF, DF[[col]])
m <- lapply(sp, function(.m) zoo::na.locf(.m, fromLast = TRUE))
m <- lapply(m, function(.m) zoo::na.locf(.m))
m <- do.call(rbind, m)
row.names(m) <- NULL
m
}
m <- merge(df1, df2, all = TRUE)
m$country <- zoo::na.locf(m$country)
m$country_code <- zoo::na.locf(m$country_code)
m <- fun(m, "country_code")
m <- m[!duplicated(m), ]
m
# country_code country company_name cost1 cost2 tier
#1 BR Brazil Test <NA> 0.0819 2
#2 FR France Test <NA> 0.09945 1
#4 US USA Test <NA> 0.1053 1
df1 <-
structure(list(company_name = structure(c(1L, 1L, 1L), .Label = "Test", class = "factor"),
country_code = structure(c(2L, 1L, NA), .Label = c("BR",
"FR"), class = "factor"), country = structure(c(NA, 1L, 2L
), .Label = c("Brazil", "USA"), class = "factor"), cost1 = c(NA,
NA, NA), cost2 = c(0.09945, 0.0819, 0.1053)), .Names = c("company_name",
"country_code", "country", "cost1", "cost2"), class = "data.frame", row.names = c("1",
"2", "3"))
Related
My two dataframes are:
df1<-structure(list(header1 = structure(1:4, .Label = c("a", "b",
"c", "d"), class = "factor")), class = "data.frame", row.names = c(NA,
-4L))
and
df2<-structure(list(sample_x = structure(c(1L, 1L, 2L, 3L), .Label = c("0",
"a", "c"), class = "factor"), sample_y = structure(c(1L, 3L,
2L, 4L), .Label = c("0", "a", "m", "t"), class = "factor"), sample_z = structure(c(3L,
2L, 1L, 1L), .Label = c("0", "a", "c"), class = "factor")), class = "data.frame", row.names = c(NA,
-4L))
0s in df2 means no values.
Now I want to overlap df1 and df2 to make an output dataframe(df3):
df3<-structure(list(sample_x = c(2L, 2L, 0L), sample_y = c(1L, 3L,
2L), sample_z = c(2L, 2L, 0L)), class = "data.frame", row.names = c("overlap_df1_df2",
"unique_df1", "unique_df2"))
I tried the datatable function foverlaps:
setkeyv(df1, names(df1))
setkeyv(df2, names(df2))
df3<-foverlaps(df1,df2)
But seems like I need to have some common column names in these two dataframes, which is obviously not the case.
Thank you!
Loop through columns, and use set operations:
sapply(df2, function(i){
x = i[ !is.na(i) ]
o = intersect(df1$header1, x)
u_df1 = setdiff(df1$header1, o)
u_df2 = setdiff(x, o)
c(o = length(o),
u_df1 = length(u_df1),
u_df2 = length(u_df2))
})
# sample_x sample_y sample_z
# o 2 1 2
# u_df1 2 3 2
# u_df2 0 2 0
A solution using map:
library(purrr)
rbind(
overlap = map_dbl(df2, ~length(intersect(df1$header1, .x))),
unique_df1 = map_dbl(df2, ~length(setdiff(df1$header1, .x))),
unique_df2 = unique_df1 - overlap
)
sample_x sample_y sample_z
overlap 2 1 2
unique_df1 2 3 2
unique_df2 0 2 0
My input file is:
input_file <- structure(list(species = structure(1:3, .Label = c("x", "y",
"z"), class = "factor"), header1 = c(0L, 1L, 0L), header2 = c(0L,
1L, 1L), header3 = c(1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-3L))
Here 1 and 0 indicate presence and absence.
Now, I need to convert this file (based on presence - absence values) to:
output_file <- structure(list(header1 = structure(c(2L, 1L, 1L), .Label = c("",
"y"), class = "factor"), header2 = structure(c(2L, 3L, 1L), .Label = c("",
"y", "z"), class = "factor"), header3 = structure(1:3, .Label = c("x",
"y", "z"), class = "factor")), class = "data.frame", row.names = c(NA,
-3L))
For this, first I try to melt my input file using reshape2:
library(reshape2)
df2 <- melt(input_file, id.var = "species")
Now I am not sure how to create a dataframe to get my desired output.
Thanks!
since you are using reshape2 you could do:
library(reshape2)
dcast(subset(df1,value>0),ave(value,variable,FUN = seq_along)~variable,value.var = "species")[-1]
header1 header2 header3
1 y y x
2 <NA> z y
3 <NA> <NA> z
You can then replace the NA with the empty string
In base R, you could do:
df1 <- subset(reshape(input_file,-1,sep="",dir="long",idvar = "species"),header>0)
reshape(transform(df1,header = ave(time,time,FUN = seq_along)),dir="wide",idvar = "header",sep="")[-1]
species1 species2 species3
y.1 y y x
z.2 <NA> z y
z.3 <NA> <NA> z
Here's a base R solution. It first does an ifelse on each row. If it finds a 1 it replaces it with the species name. If it finds a zero it writes a blank. The species column is then removed. The second line just ensures that any empty cells are moved to the bottom of the columns.
m <- t(apply(input_file, 1, function(x) ifelse(x == "1", x[1], ""))[-1,])
df <- as.data.frame(apply(m, 2, function(x) x[order(-nchar(x))]))
So we can see this matches your output file:
df
#> header1 header2 header3
#> 1 y y x
#> 2 z y
#> 3 z
identical(df, output_file)
#> [1] TRUE
I would like to join repeatedly between two tables. Here is the table.
structure(list(key = structure(1:4, .Label = c("A", "B", "C", "D"),
class = "factor")), class = "data.frame", row.names = c(NA,
-4L))
structure(list(key = structure(c(1L, 2L, 2L, 3L), .Label = c("A",
"B", "C"), class = "factor"), source = structure(c(1L, 1L, 2L, 2L), .Label = c("a", "b"), class = "factor"), value = c(1L, 1L, 2L, 2L)), class = "data.frame", row.names = c(NA, -4L))
<joined>
key
A
B
C
D
<joining>
key source value
A a 1
B a 1
B b 2
C b 2
If I use left_join function like left_join(joined, joining, by = "key"), the results is here.
key source value
1 A a 1
2 B a 1
3 B b 2
4 C b 2
5 D <NA> NA
However, I want to join grouping by "source". My expected results are here.
joining_a <- joining %>%
filter(source == "a")
joining_b <- joining %>%
filter(source == "b")
left_join(joined, joining_a, by = "key")
left_join(joined, joining_b, by = "key")
bind_rows(left_join(joined, joining_a, by = "key"), left_join(joined, joining_b, by = "key"))
key source value
1 A a 1
2 B a 1
3 C <NA> NA
4 D <NA> NA
5 A <NA> NA
6 B b 2
7 C b 2
8 D <NA> NA
How do I join the tables not dividing these tables?
We can group_split(or split from base R) the 'joining' into a list and then do the left_join with 'joined' using map
library(tidyverse)
joining %>%
group_split(source) %>%
map_dfr(~ left_join(joined, .x, by = 'key'))
# key source value
#1 A a 1
#2 B a 1
#3 C <NA> NA
#4 D <NA> NA
#5 A <NA> NA
#6 B b 2
#7 C b 2
#8 D <NA> NA
Or without a lambda function
joining %>%
group_split(source) %>%
map_dfr(left_join, x = joined, by = 'key')
data
joined <- structure(list(key = structure(1:4, .Label = c("A", "B", "C",
"D"), class = "factor")), class = "data.frame", row.names = c(NA,
-4L))
joining <- structure(list(key = structure(c(1L, 2L, 2L, 3L),
.Label = c("A",
"B", "C"), class = "factor"), source = structure(c(1L, 1L, 2L,
2L), .Label = c("a", "b"), class = "factor"), value = c(1L, 1L,
2L, 2L)), class = "data.frame", row.names = c(NA, -4L))
I am experiencing a little problem using the matches function from dplyr package.
From this dataset, I would like to extract the column names starting with enj
enj1 enj2 Enjm
bbc 1 1 2
bca 1 1 2
With grepl, I can do this
dt[, grepl('enj', colnames(dt))]
and get
enj1 enj2
bbc 1 1
bca 1 1
However the function matches does not give me the correct answer
library(dplyr)
dt %>% select(matches('enj') )
# or
dt %>% select(matches('^enj') )
Any idea why ?
dt = structure(list(enj1 = structure(c(1L, 1L), .Names = c("bbc",
"bca"), .Label = "1", class = "factor"), enj2 = structure(c(1L,
1L), .Names = c("bbc", "bca"), .Label = "1", class = "factor"),
Enjm = structure(c(1L, 1L), .Names = c("bbc", "bca"), .Label = "2", class = "factor")), .Names = c("enj1",
"enj2", "Enjm"), row.names = c("bbc", "bca"), class = "data.frame")
It's because you didn't set ignore.case = F.
> dt %>% select(matches('^enj', ignore.case = F) )
enj1 enj2
bbc 1 1
bca 1 1
>
I would like to compare two data sets and identify specific instances of discrepancies between them (i.e., which variables were different).
While I have found out how to identify which records are not identical between the two data sets (using the function detailed here: http://www.cookbook-r.com/Manipulating_data/Comparing_data_frames/), I'm not sure how to flag which variables are different.
E.g.
Data set A:
id name dob vaccinedate vaccinename dose
100000 John Doe 1/1/2000 5/20/2012 MMR 4
100001 Jane Doe 7/3/2011 3/14/2013 VARICELLA 1
Data set B:
id name dob vaccinedate vaccinename dose
100000 John Doe 1/1/2000 5/20/2012 MMR 3
100001 Jane Doee 7/3/2011 3/24/2013 VARICELLA 1
100002 John Smith 2/5/2010 7/13/2013 HEPB 3
I want to identify which records are different, and which specific variable(s) have discrepancies. For example, the John Doe record has 1 discrepancy in dose, and the Jane Doe record has 2 discrepancies: in name and vaccinedate. Also, data set B has one additional record that was not in data set A, and I would want to identify these instances as well.
In the end, the goal is to find the frequency of the "types" of errors, e.g. how many records have a discrepancy in vaccinedate, vaccinename, dose, etc.
Thanks!
This should get you started, but there may be more elegant solutions.
First, establish df1 and df2 so others can reproduce quickly:
df1 <- structure(list(id = 100000:100001, name = structure(c(2L, 1L), .Label = c("Jane Doe","John Doe"), class = "factor"), dob = structure(1:2, .Label = c("1/1/2000", "7/3/2011"), class = "factor"), vaccinedate = structure(c(2L, 1L), .Label = c("3/14/2013", "5/20/2012"), class = "factor"), vaccinename = structure(1:2, .Label = c("MMR", "VARICELLA"), class = "factor"), dose = c(4L, 1L)), .Names = c("id", "name", "dob", "vaccinedate", "vaccinename", "dose"), class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(id = 100000:100002, name = structure(c(2L, 1L, 3L), .Label = c("Jane Doee", "John Doe", "John Smith"), class = "factor"), dob = structure(c(1L, 3L, 2L), .Label = c("1/1/2000", "2/5/2010", "7/3/2011"), class = "factor"), vaccinedate = structure(c(2L, 1L, 3L), .Label = c("3/24/2013", "5/20/2012", "7/13/2013"), class = "factor"), vaccinename = structure(c(2L, 3L, 1L), .Label = c("HEPB", "MMR", "VARICELLA"), class = "factor"), dose = c(3L, 1L, 3L)), .Names = c("id", "name", "dob", "vaccinedate", "vaccinename", "dose"), class = "data.frame", row.names = c(NA, -3L))
Next, get the discrepancies from df1 to df2 via mapply and setdiff. That is, what's in set one that's not in set two:
discrep <- mapply(setdiff, df1, df2)
discrep
# $id
# integer(0)
#
# $name
# [1] "Jane Doe"
#
# $dob
# character(0)
#
# $vaccinedate
# [1] "3/14/2013"
#
# $vaccinename
# character(0)
#
# $dose
# [1] 4
To count them up we can use sapply:
num.discrep <- sapply(discrep, length)
num.discrep
# id name dob vaccinedate vaccinename dose
# 0 1 0 1 0 1
Per your question on obtaining id's in set two that are not in set one, you could reverse the process with mapply(setdiff, df2, df1) or if it's simply an exercise of ids only you could do setdiff(df2$id, df1$id).
For more on R's functional functions (e.g., mapply, sapply, lapply, etc.) see this post.
Updating with a purrr solution:
map2(df1, df2, setdiff) %>%
map_int(length)
One possibility. First, find out which ids both datasets have in common. The simplest way to do this is:
commonID<-intersect(A$id,B$id)
Then you can determine which rows are missing from A by:
> B[!B$id %in% commonID,]
# id name dob vaccinedate vaccinename dose
# 3 100002 John Smith 2/5/2010 7/13/2013 HEPB 3
Next, you can restrict both datasets to the ids they have in common.
Acommon<-A[A$id %in% commonID,]
Bcommon<-B[B$id %in% commonID,]
If you can't assume that the id's are in the right order, then sort them both:
Acommon<-Acommon[order(Acommon$id),]
Bcommon<-Bcommon[order(Bcommon$id),]
Now you can see what fields are different like this.
diffs<-Acommon != Bcommon
diffs
# id name dob vaccinedate vaccinename dose
# 1 FALSE FALSE FALSE FALSE FALSE TRUE
# 2 FALSE TRUE FALSE TRUE FALSE FALSE
This is a logical matrix, and you can do whatever you want with it. For example, to find the total number of errors in each column:
colSums(diffs)
# id name dob vaccinedate vaccinename dose
# 0 1 0 1 0 1
To find all ids where the name is different:
Acommon$id[diffs[,"name"]]
# [1] 100001
And so on.
There is a new package call waldo
install.packages("waldo")
library(waldo)
# construct the data frames
df1 <- structure(list(id = 100000:100001, name = structure(c(2L, 1L), .Label = c("Jane Doe","John Doe"), class = "factor"), dob = structure(1:2, .Label = c("1/1/2000", "7/3/2011"), class = "factor"), vaccinedate = structure(c(2L, 1L), .Label = c("3/14/2013", "5/20/2012"), class = "factor"), vaccinename = structure(1:2, .Label = c("MMR", "VARICELLA"), class = "factor"), dose = c(4L, 1L)), .Names = c("id", "name", "dob", "vaccinedate", "vaccinename", "dose"), class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(id = 100000:100002, name = structure(c(2L, 1L, 3L), .Label = c("Jane Doee", "John Doe", "John Smith"), class = "factor"), dob = structure(c(1L, 3L, 2L), .Label = c("1/1/2000", "2/5/2010", "7/3/2011"), class = "factor"), vaccinedate = structure(c(2L, 1L, 3L), .Label = c("3/24/2013", "5/20/2012", "7/13/2013"), class = "factor"), vaccinename = structure(c(2L, 3L, 1L), .Label = c("HEPB", "MMR", "VARICELLA"), class = "factor"), dose = c(3L, 1L, 3L)), .Names = c("id", "name", "dob", "vaccinedate", "vaccinename", "dose"), class = "data.frame", row.names = c(NA, -3L))
# compare them
compare(df1,df2)
And we get:
`old` is length 2
`new` is length 3
`names(old)`: "X" "Y"
`names(new)`: "X" "Y" "Z"
`attr(old, 'row.names')`: 1 2 3
`attr(new, 'row.names')`: 1 2 3 4
`old$X`: 1 2 3
`new$X`: 1 2 3 4
`old$Y`: "a" "b" "c"
`new$Y`: "A" "b" "c" "d"
`old$Z` is absent
`new$Z` is a character vector ('k', 'l', 'm', 'n')
library(compareDF)
compare_df(dataframe1, dataframe2, c("columnname"))