I started with several raw df's with similar items ,cleaned and merged to a long format which i later combine to wide format using dplyr... However, i'm left with duplicates because i'm dealing with almost identical strings, can anyone please suggest an easier way to remove the duplicates while spreading my data.
here is a sample of my code
library(tidyverse)
library(readxl)
library(reprex)
all_data_final_wider<-all_data_final %>%
mutate(cases = case_when(cases=='X' ~ 'x', cases=='x' ~ 'x'))%>%
group_by(Species) %>%
mutate(row = row_number()) %>%
tidyr::pivot_wider(names_from = location, values_from =cases)%>%
select(-row)
and below is a dput of my sample data
structure(list(`Wall type (Kaminski 2014)` = c("", "", "hyaline",
"hyaline", "hyaline", "hyaline", "", "hyaline", "", "hyaline",
"hyaline", "", "", "porcelaneous (imperforate)", "porcelaneous (imperforate)",
"porcelaneous (imperforate)", "porcelaneous (imperforate)", "porcelaneous (imperforate)",
"", "", "", "", "", "", "", "", "", "porcelaneous (imperforate)",
"porcelaneous (imperforate)", "porcelaneous (imperforate)", "porcelaneous (imperforate)",
"porcelaneous (imperforate)", "porcelaneous (imperforate)", "porcelaneous (imperforate)",
"", "", "", "", "", "", "porcelaneous (imperforate)", "", "",
"", "porcelaneous (imperforate)", "", "", "", "", ""), Order = c("",
"", "Rotaliida", "Rotaliida", "Rotaliida", "Rotaliida", "", "Rotaliida",
"", "Rotaliida", "Rotaliida", "", "", "Miliolida", "Miliolida",
"Miliolida", "Miliolida", "Miliolida", "Miliolida", "", "", "",
"", "", "", "", "", "Miliolida", "Miliolida", "Miliolida", "Miliolida",
"Miliolida", "Miliolida", "Miliolida", "", "", "", "", "", "",
"Miliolida", "", "", "", "Miliolida", "", "", "", "", ""), Superfamily = c("",
"", "Planorbulinoidea", "Acervulinoidea", "Acervulinoidea", "Acervulinoidea",
"", "Acervulinoidea", "Acervulinoidea ", "Acervulinoidea", "Acervulinoidea",
"Milioloidea", "Milioloidea", "Milioloidea", "Milioloidea", "Milioloidea",
"Milioloidea", "Milioloidea", "", "", "", "", "", "", "", "",
"", "Milioloidea", "Milioloidea", "Milioloidea", "Milioloidea",
"Milioloidea", "Milioloidea", "Milioloidea", "", "", "", "",
"", "", "Milioloidea", "", "", "", "Milioloidea", "", "", "",
"", ""), Family = c("", "", "Planorbulinidae", "Acervulinoidae",
"Acervulinoidae", "Acervulinoidae", "", "Acervulinoidae", "Acervulinidae",
"Acervulinoidae", "Acervulinoidae", "Cribrolinoididae", "Cribrolinoididae",
"Cribrolinoididae", "Cribrolinoididae", "Hauerinidae", "Hauerinidae",
"Hauerinidae", "Hauerinidae", "", "", "", "", "", "", "", "",
"Cribrolinoididae", "Cribrolinoididae", "Cribrolinoididae", "Cribrolinoididae",
"Cribrolinoididae", "Cribrolinoididae", "Cribrolinoididae", "",
"", "", "", "", "", "Cribrolinoididae", "", "", "", "Cribrolinoididae",
"", "", "", "", ""), Genus = c("", "", "?Planorbulina", "Acervulina",
"Acervulina", "Acervulina", "", "Acervulina", "Acervulina", "Acervulina",
"Acervulina", "Adelosina", "Adelosina", "Adelosina", "Adelosina",
"Adelosina", "Adelosina", "Adelosina", "Quinqueloculina", "",
"", "", "", "", "", "", "", "Adelosina", "Adelosina", "Adelosina",
"Adelosina", "Adelosina", "Adelosina", "Adelosina", "", "", "",
"", "", "", "Adelosina", "", "", "", "Adelosina", "Adelosina",
"Adelosina", "", "", ""), Species = c("", "", "?Planorbulina sp . 1",
"Acervulina cf. A. mahabethi", "Acervulina cf. A. mahabeti",
"Acervulina inhaerens", "Acervulina inhaerens ", "Acervulina mabahethi",
"Acervulina mabahethi ", "Acervulina sp. 01", "Acervulina sp. 01",
"Adelosina bicornis ", "Adelosina bicornis ", "Adelosina carinatastriata",
"Adelosina carinatastriata", "Adelosina carinatastriata", "Adelosina carinatastriata",
"Adelosina carinatastriata", "Adelosina carinatastriata", "Adelosina carinatastriata ",
"Adelosina carinatastriata ", "Adelosina carinatastriata ", "Adelosina carinatastriata ",
"Adelosina carinatastriata ", "Adelosina carinatastriata ", "Adelosina carinatastriata ",
"Adelosina carinatastriata ", "Adelosina cf. A. mediterranensis",
"Adelosina crassicarinata", "Adelosina crassicarinata", "Adelosina crassicarinata",
"Adelosina crassicarinata", "Adelosina dagornae", "Adelosina dagornae",
"Adelosina dagornae", "Adelosina dagornae", "Adelosina dagornae",
"Adelosina dagornae", "Adelosina dagornae", "Adelosina dagornae",
"Adelosina echinata", "Adelosina echinata ", "Adelosina echinata ",
"Adelosina echinata ", "Adelosina honghensis", "Adelosina honghensis",
"Adelosina honghensis", "Adelosina honghensis ", "Adelosina honghensis ",
"Adelosina honghensis "), authority = c("Haynesina sp.", "Haynesina sp.",
"d'Orbigny, 1826", " Said, 1949 ", "", "Schulze, 1854", "Schulze, 1854",
" Said, 1949 ", "Said, 1949 ", "Schultze, 1854", "", "Walker & Jacob, 1798 ",
"Walker & Jacob, 1798 ", " Wiesner, 1923 ", " Wiesner, 1923 ",
" Wiesner, 1923 ", " Wiesner, 1923 ", " Wiesner, 1923 ", "Wiesner, 1923",
"Wiesner 1923 ", "Wiesner 1923 ", "Wiesner 1923 ", "Wiesner 1923 ",
"Wiesner 1923 ", "Wiesner 1923 ", "Wiesner 1923 ", "Wiesner 1923 ",
" Le Calvez & Le Calvez, 1958 ", "", "", "", "", "", "", "Levi et al. 1990 ",
"Levi et al. 1990 ", "Levi et al. 1990 ", "Levi et al. 1990 ",
"Levi et al. 1990 ", "Levi et al. 1990 ", "", "d'Orbigny, 1826",
"d'Orbigny, 1826", "d'Orbigny, 1826", "", "", "", "Lak, 1982",
"Lak, 1982", "Lak, 1982"), location = c(" Parkar and Gischler 2015 ",
"Present study", "Cherif et al. 1997", "Amao et al. 2016 PG",
"Amao_et_al_2019_Persian_Gulf_paper", "Murray 1965", " Shublak 1977 ",
"Parker and Gischler 2015", " Parkar and Gischler 2015 ", "Amao et al. 2016 PG",
"Amao_et_al_2019_Persian_Gulf_paper", " Shublak 1977 ", "Khader 2020 ",
"Al-Zamel et al 1996", "Al-Zamel et al 2009", "Parker and Gischler 2015",
"Amao et al. 2016 MP", "Amao et al. 2016 Salwa", "Amao_et_al_2019_baseline_paper",
"Al-Zamel et al. 1996 ", "Khader 1997 ", " Cherif et al. 1997 ",
"Al-Ghadban 2000 ", "Al-Zamel et al. 2009 ", "Al-Theyabi 2012b ",
"Al-Enezi et al. 2019 ", "Khader 2020 ", "Amao et al. 2016 MP",
"Al-Zamel et al 1996", "Cherif et al. 1997", "Al-Zamel & Cherif 1998",
"Al-Enezi & Frontalini 2015", "Al-Zamel et al 2009", "Al-Enezi & Frontalini 2015",
"Khader 1997 ", "Al-Ghadban 2000 ", "Al-Zamel et al. 2009 ",
"Al-Ammar 2011 ", "Al-Enezi and Frontalini 2015 ", "Khader 2020 ",
"Cherif et al. 1997", "Al-Shuaibi 1997 ", "Al-Ghadban 2000 ",
"Khader 2020 ", "Cherif et al. 1997", "Clark and Keiji 1975",
"Nabavi 2014", " Cherif et al. 1997 ", "Al-Ghadban 2000 ",
"Khader 2020 "), cases = c("X", "X", "x", "x", "x", "x", "X",
"x", "X", "x", "x", "X", "X", "x", "x", "x", "x", "x", "x", "X",
"X", "X", "X", "X", "X", "X", "X", "x", "x", "x", "x", "x", "x",
"x", "X", "X", "X", "X", "X", "X", "x", "X", "X", "X", "x", "x",
"x", "X", "X", "X")), row.names = c(NA, -50L), class = c("tbl_df",
"tbl", "data.frame"))
At the moment, my result look like Before but my target is After
Thank you in anticipation for your help.
As #hendrikvanb points our, your duplicate output rows are not only due to strings, but also incomplete data and slight differences in some of your input strings. Even if two strings contain the same information for a human reader, R treats them as different unless every single character is the same. Once we resolve this the solution is much easier.
Step 1: ensure entries with similar names have the same name
The following code begins with some simple tidying (removing excess white space, making everything lower case). It then searches your table for text that is similar and for every pair asks if you want to replace one with the other.
E.g. if you dataset contains "levi et al. 1990" and "levi et al 1990" one with a full stop and the other without, you will receive a message:
Do you want to replace "levi et al. 1990" with "levi et al 1990"?
You will also be asked the same question in reverse order. If you click 'yes' then all instances of the first will be replaced by the second in your database.
library(dplyr)
library(tidyr)
# standardise
standardized <- all_data_final %>%
rename(walltype = `Wall type (Kaminski 2014)`) %>% # first column in example data has odd name
mutate_all(as.character) %>% # ensures all columns are string not factor
mutate_all(trimws) %>% # leading and trailing white space
mutate_all(function(x){gsub(" +"," ",x)}) %>% # remove internal duplicate spaces
mutate_all(tolower) %>% # cast everything to lower
mutate(row = row_number())
# prompt user to merge text that is very close together
tollerance = 2
cols <- c("walltype", "Order", "Superfamily", "Family", "Genus", "Species", "authority", "location")
for(col in cols){
unique_vals = standardized[[col]] %>% unique() %>% sort()
for(val in unique_vals){
for(val2 in unique_vals){
# check if text strings are within edit distance of each other
if(adist(val, val2) > 0 & adist(val, val2) <= tollerance){
msg = paste0("Do you want [", val, "] replaced with [", val2, "] ?")
ans = FALSE
ans = askYesNo(msg) # ask user for every pair of close values
if(ans)
standardized <- mutate_all(standardized, function(x){ifelse(x == val, val2, x)})
}
}
}
}
You can control the sensitivity of this check by adjusting the tollerance parameter. You can think of it as the number of characters between the correct text and a spelling mistake.
Step 2: keep category text information where available
The goal here is to ensure that if one record of the species has an order, family, genus, or authority then this appears on the final table. We can do this by asking for the maximum order/family/genus per species.
When working with text, max returns the last record alphabetically. Blank or white space gets sorted to the top first, hence we must use max as min will return empty text fields.
The code for this is merged into step 3.
Step 3: keep case mark where available
By converting the case column to numeric, we can summarise across cases looking for a maximum value of 1. In some cases NA or NULL gets treated as -Inf so we also handle this.
The following code resolves step 2 and 3 in the same summarise_all statement.
# collapse
final_result <- standardized %>%
mutate(cases = ifelse(!is.na(cases), 1, 0)) %>%
pivot_wider(names_from = location, values_from = cases) %>%
group_by(Species) %>%
summarise_all(max, na.rm = TRUE) %>% # hack, ideally we'd handle strings and numbers differently
mutate_all(function(x){ifelse(is.infinite(x), NA, x)}) # gets rid of -Inf caused by summarise_all
Here is the dput output I get from this code:
structure(list(Species = c("", "?planorbulina sp . 1", "acervulina cf. a. mahabethi",
"acervulina inhaerens", "acervulina mabahethi", "acervulina sp. 01",
"adelosina bicornis", "adelosina carinatastriata", "adelosina cf. a. mediterranensis",
"adelosina crassicarinata", "adelosina dagornae", "adelosina echinata",
"adelosina honghensis"), walltype = c("", "hyaline", "hyaline",
"hyaline", "hyaline", "hyaline", "", "porcelaneous (imperforate)",
"porcelaneous (imperforate)", "porcelaneous (imperforate)", "porcelaneous (imperforate)",
"porcelaneous (imperforate)", "porcelaneous (imperforate)"),
Order = c("", "rotaliida", "rotaliida", "rotaliida", "rotaliida",
"rotaliida", "", "miliolida", "miliolida", "miliolida", "miliolida",
"miliolida", "miliolida"), Superfamily = c("", "planorbulinoidea",
"acervulinoidea", "acervulinoidea", "acervulinoidea", "acervulinoidea",
"milioloidea", "milioloidea", "milioloidea", "milioloidea",
"milioloidea", "milioloidea", "milioloidea"), Family = c("",
"planorbulinidae", "acervulinidae", "acervulinidae", "acervulinidae",
"acervulinidae", "cribrolinoididae", "hauerinidae", "cribrolinoididae",
"cribrolinoididae", "cribrolinoididae", "cribrolinoididae",
"cribrolinoididae"), Genus = c("", "?planorbulina", "acervulina",
"acervulina", "acervulina", "acervulina", "adelosina", "quinqueloculina",
"adelosina", "adelosina", "adelosina", "adelosina", "adelosina"
), authority = c("haynesina sp.", "d'orbigny, 1826", "said, 1949",
"schultze, 1854", "said, 1949", "schultze, 1854", "walker & jacob, 1798",
"wiesner 1923", "le calvez & le calvez, 1958", "", "levi et al. 1990",
"d'orbigny, 1826", "lak, 1982"), row = c(2L, 3L, 5L, 7L,
9L, 11L, 13L, 27L, 28L, 32L, 40L, 44L, 50L), `parkar and gischler 2015` = c(1,
NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA), `present study` = c(1,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), `cherif et al. 1997` = c(NA,
1, NA, NA, NA, NA, NA, 1, NA, 1, NA, 1, 1), `amao et al. 2016 mp` = c(NA,
NA, 1, NA, NA, 1, NA, 1, 1, NA, NA, NA, NA), amao_et_al_2019_persian_gulf_paper = c(NA,
NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA), `murray 1965` = c(NA,
NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA), `shublak 1977` = c(NA,
NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA), `khader 2020` = c(NA,
NA, NA, NA, NA, NA, 1, 1, NA, NA, 1, 1, 1), `al-zamel et al 1996` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA), `al-zamel et al 2009` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA), `amao et al. 2016 salwa` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA), amao_et_al_2019_baseline_paper = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA), `khader 1997` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA), `al-ghadban 2000` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, 1, 1), `al-theyabi 2012b` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA), `al-enezi et al. 2019` = c(NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA), `al-zamel & cherif 1998` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA), `al-enezi & frontalini 2015` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, NA, NA), `al-ammar 2011` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA), `al-enezi and frontalini 2015` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA), `al-shuaibi 1997` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA), `clark and keiji 1975` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1), `nabavi 2014` = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -13L))
...even if you decide to use just the species column ignoring every other column.e. Species, location and cases to pivot wide, it still doesn't help.
Actually, with minimal wrangling, it does help.
This is more complex than your comment appear to suggest.
I don't believe it is:
# load libraries
library(tidyverse)
# define data using the structure posted in the initial question
# create all_data_final_wider by taking all_data_final %>% remove all
# leading/trailing white space %>% convert cases column to lowercase %>% select
# columns to retain %>% remove exact duplicates %>% pivot from long to wide
all_data_final_wider <- all_data_final %>%
mutate_all(str_squish) %>%
mutate(cases = str_to_lower(cases)) %>%
select(Species, location, cases) %>%
distinct() %>%
pivot_wider(names_from = location, values_from = cases)
# prove that there are as many rows in all_data_final_wider as there are
# distinct spellings of the Species column
nrow(all_data_final_wider) == length(unique(all_data_final_wider$Species))
#> [1] TRUE
So I stand by my comments:
You'll need to fix these and all other inconsistencies in the input data if you expect to get sensible results from pivot_wider()
Related
In a nutshell - I have multiple columns in my data frame and some of the columns have string data that spill into the rows below, which means that those near-empty rows only have info for those spillover columns. I would like to merge the rows, and combine all the string data into that specific cell for that column with the spillover issue (I need to do this all in R please...). I also have this problem in different columns, and it does not happen in every row.... This is hard to explain with words, but my output below explains the problem the best. I figured that a dput output would be better than pasting a table here so that people could actually use this with code. This is a very simplified version of my data frame and the problem.
structure(list(SECTION = c(10207L, NA, 14097L, NA, NA, NA, NA,
21290L, NA, 3359L, NA, NA, NA, NA, 50903L, NA), SCHOOL = c("ACAD",
"", "ACCT", "", "", "", "", "ANSC", "", "LAW", "", "", "", "",
"XPPD", "PPD"), COURSE_CODE = c("ACAD-181", "", "ACCT-410", "",
"", "", "", "PR-463", "", "LAW-680A", "", "", "", "", "PPDE-630",
""), COURSE_TITLE = c("Disruptive Innovation", "", "Foundations of Accounting",
"", "", "", "", "Strategic Public Relations Research, Analysis",
"and Insights", "Review of Law and Social Justice Editing", "",
"", "", "", "Community Health Planning", ""), INSTRUCTOR_NAME = c("Smith, Tim",
"Bob, Scott", "Gem, Silvia", "", "", "", "", "OBrien, James",
"", "Harvey, Tony", "", "", "", "", "Sloth, Ryan", ""), ASSIGNED_ROOM = c("IYH210/211",
"", "ONLINE", "", "", "", "", "ONLINE", "", "ONLINE", "", "",
"", "", "ONLINE", ""), TOTAL_ENR = c(32L, NA, 55L, NA, NA, NA,
NA, 17L, NA, 13L, NA, NA, NA, NA, 16L, NA), COURSE_DESCRIPTION = c("Critical approaches to social and cultural changes.",
"", "Non-technical presentation of accounting for users of accounting",
"information; introduction to financial and managerial accounting.",
"Not open to students with course credits in accounting. Not",
"available for unit or course credit toward a degree in accounting",
"or business administration.", "Identification of key strategic insights.",
"", "Supervision of research and writing, and final editing of articles",
"and comments for publication in the Review of Law and Social",
"Justice. For officers of the Review. Open to law students only.",
"Graded IP to CR/D/F.", "", "The role of planning in sustaining community health.",
"")), class = "data.frame", row.names = c(NA, -16L))
I think this will work.
library(tidyverse)
X <- structure(list(SECTION = c(10207L, NA, 14097L, NA, NA, NA, NA, 21290L, NA, 3359L, NA, NA, NA, NA, 50903L, NA),
SCHOOL = c("ACAD", "", "ACCT", "", "", "", "", "ANSC", "", "LAW", "", "", "", "", "XPPD", "PPD"),
COURSE_CODE = c("ACAD-181", "", "ACCT-410", "", "", "", "", "PR-463", "", "LAW-680A", "", "", "", "", "PPDE-630", ""),
COURSE_TITLE = c("Disruptive Innovation", "", "Foundations of Accounting", "", "", "", "", "Strategic Public Relations Research, Analysis", "and Insights", "Review of Law and Social Justice Editing", "", "", "", "", "Community Health Planning", ""),
INSTRUCTOR_NAME = c("Smith, Tim", "Bob, Scott", "Gem, Silvia", "", "", "", "", "OBrien, James", "", "Harvey, Tony", "", "", "", "", "Sloth, Ryan", ""),
ASSIGNED_ROOM = c("IYH210/211", "", "ONLINE", "", "", "", "", "ONLINE", "", "ONLINE", "", "", "", "", "ONLINE", ""),
TOTAL_ENR = c(32L, NA, 55L, NA, NA, NA, NA, 17L, NA, 13L, NA, NA, NA, NA, 16L, NA),
COURSE_DESCRIPTION = c("Critical approaches to social and cultural changes.", "", "Non-technical presentation of accounting for users of accounting", "information; introduction to financial and managerial accounting.", "Not open to students with course credits in accounting. Not", "available for unit or course credit toward a degree in accounting", "or business administration.", "Identification of key strategic insights.", "", "Supervision of research and writing, and final editing of articles", "and comments for publication in the Review of Law and Social", "Justice. For officers of the Review. Open to law students only.", "Graded IP to CR/D/F.", "", "The role of planning in sustaining community health.", "")),
class = "data.frame", row.names = c(NA, -16L))
X_collapsed <- X
for(i in seq(nrow(X), 2, -1)) { # Work on the table in bottom to top so we can merge the values
if(is.na(X_collapsed[i, "SECTION"])) { # only work on rows with NA in the SECTION column
# Work on the current row and the previous row.
# Don't modify numeric columns (don't want to merge NA values).
# Use lead() to check across rows, and turn NA values into an empty string.
# Use paste() to combine the row values.
# use trim() to get rid of any excess white space produced.
X_collapsed[i-1,] <- (X_collapsed[c(i-1,i),] %>%
mutate(across(.fns = ~ ifelse(is.numeric(.x), .x, trim(paste(.x, ifelse(is.na(lead(.x)), "", lead(.x)))))))
)[1, ]
}
}
X_collapsed <- X_collapsed %>%
filter(!is.na(SECTION)) # remove rows we don't want.
X_collapsed
This also removes extra whitespace due to the use of trim(). Without it you may end up with trailing spaces.
I am Mapping column_data to master and if column value is present in master than it saves it Key
ex:Parent for P and Child for C
Problem is i am getting the output but output is indexed differently
DATA
column_data <- c("", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "P", "C", "C")
master <- list("Parent" = c("P"),
"Child" = c("C")
)
CODE
library(dplyr)
df <- data.frame("column" = column_data)
df <-stack(master) %>%
type.convert(as.is = TRUE) %>%
right_join(df, by = c('values' = 'column')) %>%
mutate(output = coalesce(ind, values))
This Should be the output:
structure(list(values = c("", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "P", "C", "C"), ind = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Parent",
"Child", "Child"), output = c("", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "Parent", "Child", "Child")), class = "data.frame", row.names = c(NA,
-19L))
but instead i get this as output:
structure(list(values = c("P", "C", "C", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", ""), ind = c("Parent",
"Child", "Child", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA), output = c("Parent", "Child", "Child", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "")), row.names = c(NA,
-19L), class = "data.frame")
With dplyr, if you do a right_join(x, y) then the result will include a subset of the matched rows for x, then unmatched rows for y.
From R documentation on mutating joins, the value returned will be:
An object of the same type as x. The order of the rows and columns of
x is preserved as much as possible. The output has the following
properties:
For inner_join(), a subset of x rows. For left_join(), all x rows. For
right_join(), a subset of x rows, followed by unmatched y rows. For
full_join(), all x rows, followed by unmatched y rows.
That is why you have the 3 matched rows at the beginning of your resulting data.frame.
To get the desired result preserving the row order of df, try a left_join as follows:
df2 <- stack(master) %>%
type.convert(as.is = TRUE)
df %>%
left_join(df2, by = c('column' = 'values')) %>%
mutate(output = coalesce(ind, column))
Output
column ind output
1 <NA>
2 <NA>
3 <NA>
4 <NA>
5 <NA>
6 <NA>
7 <NA>
8 <NA>
9 <NA>
10 <NA>
11 <NA>
12 <NA>
13 <NA>
14 <NA>
15 <NA>
16 <NA>
17 P Parent Parent
18 C Child Child
19 C Child Child
My data is as follows:
DF <- structure(list(toberevised = c("[Money amounts are in thousands of dollars]",
NA, NA, NA, "Item", NA, NA, NA, NA, "Number of returns", "Number of joint returns",
"Number with paid preparer's signature", "Number of exemptions",
"Adjusted gross income (AGI) [3]", "Salaries and wages in AGI: [4] Number",
"Salaries and wages in AGI: Amount", "Taxable interest: Number",
"Taxable interest: Amount", "Ordinary dividends: Number", "Ordinary dividends: Amount"
), ...2 = c("UNITED STATES [2]", NA, NA, NA, "All returns", NA,
NA, "1", NA, "135257620", "52607676", "80455243", "273738434",
"7364640131", "114060887", "5161583318", "59553985", "161324824",
"31158675", "164247298"), ...3 = c(NA, NA, NA, NA, "Under", "$50,000 [1]",
NA, "2", NA, "92150166", "20743943", "53622647", "159649737",
"1797097083", "75422766", "1541276272", "28527550", "39043002",
"13174923", "23867893"), ...4 = c(NA, NA, "Size of adjusted gross income",
NA, "50000", "under", "75000", "3", NA, "18221115", "11329459",
"11025624", "44189517", "1119634632", "16299827", "896339313",
"10891905", "16353293", "5255958", "12810282"), ...5 = c(NA,
NA, NA, NA, "75000", "under", "100000", "4", NA, "10499106",
"8296546", "6260725", "28555195", "905336768", "9520214", "721137490",
"7636612", "12852148", "4095938", "11524298"), ...6 = c(NA, NA,
NA, NA, "100000", "under", "200000", "5", NA, "10797979", "9193700",
"6678965", "30919226", "1429575727", "9782173", "1083175205",
"9092673", "23160862", "5824522", "25842394"), ...7 = c(NA, NA,
NA, NA, "200000", "or more", NA, "6", NA, "3589254", "3044028",
"2867282", "10424759", "2112995921", "3035907", "919655038",
"3405245", "69915518", "2807334", "90202431")), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
All I would like to do is concatenate for each column, rows 5, 6 and 7. I tried:
DF[,5:7] <- lapply(DF[,5:7], paste(DF[,5:7],collapse=" "))
But I get the error:
Error in get(as.character(FUN), mode = "function", envir = envir) :
variable names are limited to 10000 bytes
This happens even when I concatenate one row it with another empty row instead (which obviously should not be much more bytes)!
lapply(DF[5:7, ], paste, collapse=" ")
Let's say I have the following data:
structure(list(political_spectrum = c(5L, 15L, 12L, 30L, 100L,
0L, 27L, 52L, 38L, 64L, 0L, 0L, 76L, 50L, 16L, 16L, 0L, 23L,
0L, 25L, 68L, 50L, 4L, 0L, 50L), politics_today = c("Independent",
"Strong Democrat", "Weak Democrat", "Weak Democrat", "Weak Republican",
"Strong Democrat", "Weak Democrat", "Weak Democrat", "Independent",
"Weak Democrat", "Strong Democrat", "Independent", "Weak Republican",
"Weak Democrat", "Weak Democrat", "Strong Democrat", "Strong Democrat",
"Strong Democrat", "Strong Democrat", "Strong Democrat", "Independent",
"Independent", "Strong Democrat", "Strong Democrat", "Independent"
), stranger_things_universe_mc = c("The Demagorgon", "", "",
"", "", "", "", "", "", "The Stranger Land", "The Demagorgon",
"The Upside Down", "", "", "", "", "", "The Upside Down", "The Shadowland",
"", "", "", "", "", "The Shadowland"), stranger_things_universe_answer = c("The Upside Down",
"", "", "", "", "", "", "", "", "The Upside Down", "The Upside Down",
"The Upside Down", "", "", "", "", "", "The Upside Down", "The Upside Down",
"", "", "", "", "", "The Upside Down"), stranger_things_universe_confidence = c(32L,
NA, NA, NA, NA, NA, NA, NA, NA, 67L, 94L, 89L, NA, NA, NA, NA,
NA, 51L, 10L, NA, NA, NA, NA, NA, 0L), stranger_things_universe_importance = c("Don't care at all",
"", "", "", "", "", "", "", "", "Care somewhat strongly", "Care a little",
"Care somewhat strongly", "", "", "", "", "", "Care somewhat",
"Don't care at all", "", "", "", "", "", "Don't care at all"),
tupac_mc = c("", "Biggie Smalls", "", "", "", "", "", "Biggie Smalls",
"Biggie Smalls", "", "", "Biggie Smalls", "", "", "", "",
"", "", "Biggie Smalls", "", "", "Ice Cube", "", "", ""),
tupac_answer = c("", "Biggie Smalls", "", "", "", "", "",
"Biggie Smalls", "Biggie Smalls", "", "", "Biggie Smalls",
"", "", "", "", "", "", "Biggie Smalls", "", "", "Biggie Smalls",
"", "", ""), tupac_confidence = c(NA, 70L, NA, NA, NA, NA,
NA, 71L, 76L, NA, NA, 100L, NA, NA, NA, NA, NA, NA, 100L,
NA, NA, 32L, NA, NA, NA), tupac_importance = c("", "Don't care at all",
"", "", "", "", "", "Care somewhat", "Don't care at all",
"", "", "Care strongly", "", "", "", "", "", "", "Care a little",
"", "", "Don't care at all", "", "", ""), uber_ceo_mc = c("John Zimmer",
"", "", "", "", "Travis Kalanick", "", "", "", "Travis Kalanick",
"", "", "", "", "", "", "", "John Zimmer", "Travis Kalanick",
"Travis Kalanick", "", "", "", "", ""), uber_ceo_answer = c("Travis Kalanick",
"", "", "", "", "Travis Kalanick", "", "", "", "Travis Kalanick",
"", "", "", "", "", "", "", "Travis Kalanick", "Travis Kalanick",
"Travis Kalanick", "", "", "", "", ""), uber_ceo_confidence = c(0L,
NA, NA, NA, NA, 94L, NA, NA, NA, 69L, NA, NA, NA, NA, NA,
NA, NA, 5L, 13L, 17L, NA, NA, NA, NA, NA), uber_ceo_importance = c("Don't care at all",
"", "", "", "", "Care strongly", "", "", "", "Care somewhat",
"", "", "", "", "", "", "", "Don't care at all", "Don't care at all",
"Care somewhat", "", "", "", "", ""), black_panther_mc = c("",
"T'Chaka", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "T'Chaka", "", ""), black_panther_answer = c("",
"T'Challa", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "T'Challa", "", ""), black_panther_confidence = c(NA,
63L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 34L, NA, NA), black_panther_importance = c("",
"Don't care at all", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "Care a little",
"", ""), the_office_mc = c("The Mindy Project", "", "", "",
"", "", "", "", "", "", "", "", "", "", "The Office", "",
"", "The Mindy Project", "", "", "", "", "The Office", "",
""), the_office_answer = c("The Office", "", "", "", "",
"", "", "", "", "", "", "", "", "", "The Office", "", "",
"The Office", "", "", "", "", "The Office", "", ""), the_office_confidence = c(43L,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 2L, NA,
NA, 11L, NA, NA, NA, NA, 100L, NA, NA), the_office_importance = c("Don't care at all",
"", "", "", "", "", "", "", "", "", "", "", "", "", "Don't care at all",
"", "", "Care a little", "", "", "", "", "Care a little",
"", ""), arms_manufacturing_company_mc = c("J. Brockton & Sons",
"", "", "O.F. Mossberg & Sons", "", "", "", "", "", "", "",
"", "J. Brockton & Sons", "", "", "", "", "", "", "", "",
"", "", "", "J. Brockton & Sons"), arms_manufacturing_company_answer = c("J. Brockton & Sons",
"", "", "J. Brockton & Sons", "", "", "", "", "", "", "",
"", "J. Brockton & Sons", "", "", "", "", "", "", "", "",
"", "", "", "J. Brockton & Sons"), arms_manufacturing_company_confidence = c(91L,
NA, NA, 24L, NA, NA, NA, NA, NA, NA, NA, NA, 37L, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 100L), arms_manufacturing_company_importance = c("Don't care at all",
"", "", "Don't care at all", "", "", "", "", "", "", "",
"", "Don't care at all", "", "", "", "", "", "", "", "",
"", "", "", "Don't care at all")), class = c("data.table",
"data.frame"), row.names = c(NA, -25L))
I'm trying to do something like the following:
test %>%
gather(name, value, -c('political_spectrum', 'politics_today')) %>%
filter(value != "") %>%
mutate(question_id = sub("_[^_]+$", "", name)) %>%
mutate(confidence = grepl("_confidence", name)) %>%
group_by(politics_today, question_id) %>%
summarize(mean_confidence = mean(value[confidence == "TRUE"]))
in which I get the mean_confidence values for each political affiliation, but only for specific rows in the "value" column. In order to run the mean only on "confidence" columns, I am trying to do a filter via mean(value[confidence == "TRUE"]), but am not sure the correct way to do this.
I think you need to change your code to
library(tidyverse)
test %>%
gather(name, value, -c('political_spectrum', 'politics_today')) %>%
filter(value != "") %>%
mutate(question_id = sub("_[^_]+$", "", name),
confidence = grepl("_confidence", name)) %>%
group_by(politics_today, question_id) %>%
summarize(mean_confidence = mean(as.numeric(value[confidence])))
# politics_today question_id mean_confidence
# <chr> <chr> <dbl>
# 1 Independent arms_manufacturing_company 95.5
# 2 Independent stranger_things_universe 40.3
# 3 Independent the_office 43
# 4 Independent tupac 69.3
# 5 Independent uber_ceo 0
# 6 Strong Democrat black_panther 48.5
# 7 Strong Democrat stranger_things_universe 51.7
# 8 Strong Democrat the_office 55.5
# 9 Strong Democrat tupac 85
#10 Strong Democrat uber_ceo 32.2
#11 Weak Democrat arms_manufacturing_company 24
#12 Weak Democrat stranger_things_universe 67
#13 Weak Democrat the_office 2
#14 Weak Democrat tupac 71
#15 Weak Democrat uber_ceo 69
#16 Weak Republican arms_manufacturing_company 37
Since your value column has got both numeric and character values, it gets converted to a character column so you need to change the value where confidence == TRUE to numeric.
Data frame df has 57 columns. I later read in other csv files, each of which may have the same 57, but more likely have more or fewer columns. I take the names of the original file as:
df = read.csv(...)
str = colnames(df)
I know I can take subsets of a data frame as:
file = read.csv(...)
file = file[, str]
If the columns of file have the same or greater number of columns than the original 57, this will work fine. The extra columns would simply be dropped. However, if the columns of file are fewer than the original 57, the following error arises:
Error in `[.data.frame`(file, , str) : undefined columns selected
Is there a way to take this same approach, but create columns of NA if the column does not exist in file?
EDIT: Including dput ouput for #akrun. I'm not familiar with dput so I hope this is what you were asking for:
File 1 example:
`structure(list(ObservationURI = c("http://resources.usgin.org/uri-gin/wygs/bhtemp/49-037-20341_182_12296/",
"http://resources.usgin.org/uri-gin/wygs/bhtemp/49-037-20341_215_14316/",
"http://resources.usgin.org/uri-gin/wygs/bhtemp/49-037-20341_236_16496/"
), WellName = c("1 BRADY UNIT ANADARKO E&P COMPANY LP", "1 BRADY UNIT ANADARKO E&P COMPANY LP",
"1 BRADY UNIT ANADARKO E&P COMPANY LP"), APINo = c("49-037-20341",
"49-037-20341", "49-037-20341"), HeaderURI = c("http://resources.usgin.org/uri-gin/wygs/well/3720341/",
"http://resources.usgin.org/uri-gin/wygs/well/3720341/", "http://resources.usgin.org/uri-gin/wygs/well/3720341/"
), OtherID = c(3720341, 3720341, 3720341), OtherName = c(NA,
NA, NA), BoreholeName = c(NA, NA, NA), Label = c("Temperature observation for well 3720341",
"Temperature observation for well 3720341", "Temperature observation for well 3720341"
), Operator = c("", "", ""), LeaseName = c("", "", ""), LeaseOwner = c("",
"", ""), LeaseNo = c("", "", ""), SpudDate = c("1900-01-01T00:00",
"1900-01-01T00:00", "1900-01-01T00:00"), EndedDrillingDate = c("",
"", ""), WellType = c("Oil", "Oil", "Oil"), Status = c("Producing Oil Well",
"Producing Oil Well", "Producing Oil Well"), CommodityOfInterest = c("",
"", ""), StatusDate = c("1973-05-03T00:00:00", "1973-05-03T00:00:00",
"1973-05-03T00:00:00"), Function = c(NA, NA, NA), Production = c(NA,
NA, NA), ProducingInterval = c(NA, NA, NA), ReleaseDate = c(NA,
NA, NA), Field = c("", "", ""), OtherLocationName = c("Great Divide Basin",
"Great Divide Basin", "Great Divide Basin"), County = c("Sweetwater",
"Sweetwater", "Sweetwater"), State = c("WY", "WY", "WY"), PLSS_Meridians = c(NA,
NA, NA), TWP = c("16N", "16N", "16N"), RGE = c("101W", "101W",
"101W"), Section_ = c(11, 11, 11), SectionPart = c("NENW", "NENW",
"NENW"), Parcel = c(NA, NA, NA), UTM_E = c(NA, NA, NA), UTM_N = c(NA,
NA, NA), UTMDatumZone = c(NA, NA, NA), LatDegree = c(41.38696,
41.38696, 41.38696), LongDegree = c(-108.75009, -108.75009, -108.75009
), SRS = c("EPSG:4326", "EPSG:4326", "EPSG:4326"), LocationUncertaintyStatement = c("nil:missing",
"nil:missing", "nil:missing"), LocationUncertaintyCode = c(NA,
NA, NA), LocationUncertaintyRadius = c(NA, NA, NA), DrillerTotalDepth = c(NA_real_,
NA_real_, NA_real_), DepthReferencePoint = c(NA, NA, NA), LengthUnits = c("ft",
"ft", "ft"), WellBoreShape = c(NA, NA, NA), TrueVerticalDepth = c(NA,
NA, NA), ElevationKB = c(7135, 7135, 7135), ElevationDF = c(7106,
7106, 7106), ElevationGL = c(0, 0, 0), FormationTD = c("", "",
""), BitDiameterCollar = c(NA, NA, NA), BitDiameterTD = c(NA_real_,
NA_real_, NA_real_), DiameterUnits = c("", "", ""), Notes = c("Depth of measurement assumed to be equal to driller total depth (CRC-AZGS, 2013).",
"Depth of measurement assumed to be equal to driller total depth (CRC-AZGS, 2013).",
"Depth of measurement assumed to be equal to driller total depth (CRC-AZGS, 2013)."
), MaximumRecordedTemperature = c(NA_real_, NA_real_, NA_real_
), MeasuredTemperature = c(182, 215, 236), CorrectedTemperature = c(NA_real_,
NA_real_, NA_real_), TemperatureUnits = c(FALSE, FALSE, FALSE
), TimeSinceCirculation = c(NA_real_, NA_real_, NA_real_), CirculationDuration = c(11,
12, 12), MeasurementProcedure = c("Well log", "Well log", "Well log"
), CorrectionType = c(NA, NA, NA), DepthOfMeasurement = c(-99999,
-99999, -99999), MeasurementDateTime = c("", "", ""), MeasurementFormation = c("",
"", ""), MeasurementSource = c("Richard W. Davis: Deriving geothermal parameters from bottom-hole temperatures in Wyoming\" AAPG bulletin, V. 96, No. 8 (August 2012), pp. 1579-1592",
"Richard W. Davis: Deriving geothermal parameters from bottom-hole temperatures in Wyoming\" AAPG bulletin, V. 96, No. 8 (August 2012), pp. 1579-1592",
"Richard W. Davis: Deriving geothermal parameters from bottom-hole temperatures in Wyoming\" AAPG bulletin, V. 96, No. 8 (August 2012), pp. 1579-1592"
), RelatedResource = c(NA, NA, NA), CasingLogger = c(NA, NA,
NA), CasingBottomDepthDriller = c(NA, NA, NA), CasingTopDepth = c(NA_real_,
NA_real_, NA_real_), CasingPipeDiameter = c(NA, NA, NA), CasingWeight = c(NA,
NA, NA), CasingWeightUnits = c(NA, NA, NA), CasingThickness = c(NA,
NA, NA), DrillingFluid = c("", "", ""), Salinity = c(NA_real_,
NA_real_, NA_real_), MudResistivity = c(NA_real_, NA_real_, NA_real_
), Density = c(NA_real_, NA_real_, NA_real_), FluidLevel = c(NA_real_,
NA_real_, NA_real_), pH = c(NA_real_, NA_real_, NA_real_), Viscosity = c(NA_real_,
NA_real_, NA_real_), FluidLoss = c(NA_real_, NA_real_, NA_real_
), MeasurementNotes = c(NA, NA, NA), InformationSource = c("Wyoming State Geological Survey",
"Wyoming State Geological Survey", "Wyoming State Geological Survey"
)), .Names = c("ObservationURI", "WellName", "APINo", "HeaderURI",
"OtherID", "OtherName", "BoreholeName", "Label", "Operator",
"LeaseName", "LeaseOwner", "LeaseNo", "SpudDate", "EndedDrillingDate",
"WellType", "Status", "CommodityOfInterest", "StatusDate", "Function",
"Production", "ProducingInterval", "ReleaseDate", "Field", "OtherLocationName",
"County", "State", "PLSS_Meridians", "TWP", "RGE", "Section_",
"SectionPart", "Parcel", "UTM_E", "UTM_N", "UTMDatumZone", "LatDegree",
"LongDegree", "SRS", "LocationUncertaintyStatement", "LocationUncertaintyCode",
"LocationUncertaintyRadius", "DrillerTotalDepth", "DepthReferencePoint",
"LengthUnits", "WellBoreShape", "TrueVerticalDepth", "ElevationKB",
"ElevationDF", "ElevationGL", "FormationTD", "BitDiameterCollar",
"BitDiameterTD", "DiameterUnits", "Notes", "MaximumRecordedTemperature",
"MeasuredTemperature", "CorrectedTemperature", "TemperatureUnits",
"TimeSinceCirculation", "CirculationDuration", "MeasurementProcedure",
"CorrectionType", "DepthOfMeasurement", "MeasurementDateTime",
"MeasurementFormation", "MeasurementSource", "RelatedResource",
"CasingLogger", "CasingBottomDepthDriller", "CasingTopDepth",
"CasingPipeDiameter", "CasingWeight", "CasingWeightUnits", "CasingThickness",
"DrillingFluid", "Salinity", "MudResistivity", "Density", "FluidLevel",
"pH", "Viscosity", "FluidLoss", "MeasurementNotes", "InformationSource"
), row.names = c(NA, 3L), class = "data.frame")`
File 2 example:
`structure(list(ObservationURI = c("http://resources.usgin.org/uri-gin/mags/bhtemp/UM:MA-Weston47-422036N0711640.1/",
"http://resources.usgin.org/uri-gin/mags/bhtemp/UM:MA-Dover20-421431N0711752.1/",
"http://resources.usgin.org/uri-gin/mags/bhtemp/UM:MA-Lincoln13-422440N0711815.1/"
), WellName = c("Weston47-USGS HDR19", "Dover20-USGS HDR19",
"Lincoln13-USGS HDR19"), APINo = c(NA, NA, NA), HeaderURI = c("http://resources.usgin.org/uri-gin/mags/well/Weston47-USGS_HDR19/",
"http://resources.usgin.org/uri-gin/mags/well/Dover20-USGS_HDR19/",
"http://resources.usgin.org/uri-gin/mags/well/Lincoln13-USGS_HDR19/"
), OtherID = c("", "", ""), OtherName = c("", "", ""), BoreholeName = c(NA,
NA, NA), Operator = c(NA, NA, NA), LeaseOwner = c(NA, NA, NA),
LeaseNo = c(NA, NA, NA), SpudDate = c(NA, NA, NA), EndedDrillingDate = c("",
"", ""), WellType = c("temporarily abandoned", "observation",
"observation"), Status = c("Idle", "Idle", "Idle"), CommodityOfInterest = c("Water",
"Water", "Water"), StatusDate = c("", "", ""), Function = c("production",
"monitoring", "monitoring"), Production = c(NA, NA, NA),
Field = c(NA, NA, NA), County = c("Middlesex", "Norfolk",
"Middlesex"), State = c("MA", "MA", "MA"), PLSS_Meridians = c(NA,
NA, NA), TWP = c(NA, NA, NA), RGE = c(NA, NA, NA), Section_ = c(NA,
NA, NA), SectionPart = c(NA, NA, NA), Parcel = c(NA, NA,
NA), UTM_E = c(NA, NA, NA), UTM_N = c(NA, NA, NA), LatDegree = c(42.3147771183,
42.2417748607, 42.4110851252), LongDegree = c(-71.3257301787,
-71.2975422044, -71.3034583949), SRS = c("EPSG:4326", "EPSG:4326",
"EPSG:4326"), LocationUncertaintyStatement = c("Field located on topographic map",
"Field located on topographic map", "Field located on topographic map"
), DrillerTotalDepth = c(29, 22, 20), LengthUnits = c("ft",
"ft", "ft"), WellBoreShape = c("Vertical", "Vertical", "Vertical"
), TrueVerticalDepth = c(NA, NA, NA), ElevationGL = c(140,
150, 180), BitDiameterTD = c(72, 48, 42), DiameterUnits = c("in",
"in", "in"), Notes = c("", "", ""), MeasuredTemperature = c(8,
9, 8.5), CorrectedTemperature = c(NA, NA, NA), TemperatureUnits = c("C",
"C", "C"), TimeSinceCirculation = c(NA, NA, NA), CirculationDuration = c(NA,
NA, NA), MeasurementProcedure = c("Samples collected from spigot or faucet nearest to well. Water run until temperature, pH or specific conductance stablized. Temperature measured with a mercury thermometer to nearest half degree in degrees F. Converted to degrees C for table.",
"Samples collected from spigot or faucet nearest to well. Water run until temperature, pH or specific conductance stablized. Temperature measured with a mercury thermometer to nearest half degree in degrees F. Converted to degrees C for table.",
"Samples collected from spigot or faucet nearest to well. Water run until temperature, pH or specific conductance stablized. Temperature measured with a mercury thermometer to nearest half degree in degrees F. Converted to degrees C for table."
), CorrectionType = c(NA, NA, NA), DepthOfMeasurement = c(NA,
NA, NA), MeasurementDateTime = c(NA, NA, NA), MeasurementFormation = c(NA,
NA, NA), MeasurementSource = c("Walker, Eugene H., William W. Caswell, and S. William Wandle, Jr. Hydrologic Data of the Charles River Basin",
"Walker, Eugene H., William W. Caswell, and S. William Wandle, Jr. Hydrologic Data of the Charles River Basin",
"Walker, Eugene H., William W. Caswell, and S. William Wandle, Jr. Hydrologic Data of the Charles River Basin"
), CasingLogger = c(" Massachusetts\". USGS Massachusetts Hydrologic-Data Report No. 19 (1977): 1-57. Print. ftp://eclogite.geo.umass.edu/pub/stategeologist/Products/Geothermal/BoreholeTemperatureData/DataReport19.pdf\"",
" Massachusetts\". USGS Massachusetts Hydrologic-Data Report No. 19 (1977): 1-57. Print. ftp://eclogite.geo.umass.edu/pub/stategeologist/Products/Geothermal/BoreholeTemperatureData/DataReport19.pdf\"",
" Massachusetts\". USGS Massachusetts Hydrologic-Data Report No. 19 (1977): 1-57. Print. ftp://eclogite.geo.umass.edu/pub/stategeologist/Products/Geothermal/BoreholeTemperatureData/DataReport19.pdf\""
), CasingDepthDriller = c("", "", ""), CasingPipeDiameter = c("",
"", ""), CasingWeight = c(NA, NA, NA), CasingWeightUnits = c(NA,
NA, NA), CasingThickness = c(NA, NA, NA), DrillingFluid = c(NA,
NA, NA), Salinity = c(NA, NA, NA), MudResisitivity = c(NA,
NA, NA), Density = c(NA, NA, NA), FluidLevel = c(NA, NA,
NA), pH = c(NA, NA, NA), Viscosity = c(NA, NA, NA), FluidLoss = c(NA,
NA, NA), Unnamed..66 = c(NA, NA, NA), BitDiameterCollar = c(72,
48, 42), Unnamed..68 = c(NA, NA, NA), InformationSource = c("Stephen Mabee, MA State Geologist, University of Massachusetts, 611 North Pleasant Street, Amherst MA 01003 413-545-2285",
"Stephen Mabee, MA State Geologist, University of Massachusetts, 611 North Pleasant Street, Amherst MA 01003 413-545-2285",
"Stephen Mabee, MA State Geologist, University of Massachusetts, 611 North Pleasant Street, Amherst MA 01003 413-545-2285"
)), .Names = c("ObservationURI", "WellName", "APINo", "HeaderURI",
"OtherID", "OtherName", "BoreholeName", "Operator", "LeaseOwner",
"LeaseNo", "SpudDate", "EndedDrillingDate", "WellType", "Status",
"CommodityOfInterest", "StatusDate", "Function", "Production",
"Field", "County", "State", "PLSS_Meridians", "TWP", "RGE", "Section_",
"SectionPart", "Parcel", "UTM_E", "UTM_N", "LatDegree", "LongDegree",
"SRS", "LocationUncertaintyStatement", "DrillerTotalDepth", "LengthUnits",
"WellBoreShape", "TrueVerticalDepth", "ElevationGL", "BitDiameterTD",
"DiameterUnits", "Notes", "MeasuredTemperature", "CorrectedTemperature",
"TemperatureUnits", "TimeSinceCirculation", "CirculationDuration",
"MeasurementProcedure", "CorrectionType", "DepthOfMeasurement",
"MeasurementDateTime", "MeasurementFormation", "MeasurementSource",
"CasingLogger", "CasingDepthDriller", "CasingPipeDiameter", "CasingWeight",
"CasingWeightUnits", "CasingThickness", "DrillingFluid", "Salinity",
"MudResisitivity", "Density", "FluidLevel", "pH", "Viscosity",
"FluidLoss", "Unnamed..66", "BitDiameterCollar", "Unnamed..68",
"InformationSource"), row.names = c(NA, 3L), class = "data.frame")`
We can read the datasets in a list with fread and use rbindlist from data.table with fill = TRUE and idcol argument to create a single data.table object. The fill = TRUE ensure that NA elements are created for those datasets that have lesser number of columns.
library(data.table)
#get the files from the working directory
files <- list.files(pattern = ".csv")
#read files in a loop with fread and then rbind the data.tables
rbindlist(lapply(files, fread), fill = TRUE, idcol = "grp")