Split dataframe by empty row
How about this Base R solution:
n <- rowSums(is.na(df)) == ncol(df)
cs <- cumsum(n) + 1
s <- split(df[!n, ], cs[!n])
s
#> $`1`
#> a b c d
#> 1 <NA> <NA> Var1 Var2
#> 2 <NA> <NA> Unit/1 Unit/2
#> 3 Loc_1 25:11:2020 1 <NA>
#> 4 Loc_1 26:11:2020 2 <NA>
#> 5 Loc_1 27:11:2020 3 1
#>
#> $`2`
#> a b c d
#> 7 <NA> <NA> Var3 Var1
#> 8 <NA> <NA> Unit/3 Unit/1
#> 9 Loc_2 25:11:2020 <NA> <NA>
#> 10 Loc_2 26:11:2020 1 <NA>
#> 11 Loc_2 27:11:2020 2 1
#>
#> $`3`
#> a b c d
#> 13 <NA> <NA> Var1 Var3
#> 14 <NA> <NA> Unit/1 Unit/3
#> 15 Loc_3 25:11:2020 1 <NA>
#> 16 Loc_3 26:11:2020 2 <NA>
#> 17 Loc_3 27:11:2020 3 1
You can neatly set all your data together again in a long format in this way with unpivotr
:
library(unpivotr)
library(dplyr)
library(purrr)
map_dfr(s,
~ as_cells(.x) %>%
behead("up", "var") %>%
behead("up", "uom") %>%
behead("left", "loc") %>%
behead("left", "date") %>%
# filter(!is.na(chr)) %>% # do you need the NAs?
mutate(value = as.numeric(chr)) %>%
select(var, uom, loc, date, value),
.id = "df")
#> # A tibble: 18 x 6
#> df var uom loc date value
#> <chr> <chr> <chr> <chr> <chr> <dbl>
#> 1 1 Var1 Unit/1 Loc_1 25:11:2020 1
#> 2 1 Var1 Unit/1 Loc_1 26:11:2020 2
#> 3 1 Var1 Unit/1 Loc_1 27:11:2020 3
#> 4 1 Var2 Unit/2 Loc_1 25:11:2020 NA
#> 5 1 Var2 Unit/2 Loc_1 26:11:2020 NA
#> 6 1 Var2 Unit/2 Loc_1 27:11:2020 1
#> 7 2 Var3 Unit/3 Loc_2 25:11:2020 NA
#> 8 2 Var3 Unit/3 Loc_2 26:11:2020 1
#> 9 2 Var3 Unit/3 Loc_2 27:11:2020 2
#> 10 2 Var1 Unit/1 Loc_2 25:11:2020 NA
#> 11 2 Var1 Unit/1 Loc_2 26:11:2020 NA
#> 12 2 Var1 Unit/1 Loc_2 27:11:2020 1
#> 13 3 Var1 Unit/1 Loc_3 25:11:2020 1
#> 14 3 Var1 Unit/1 Loc_3 26:11:2020 2
#> 15 3 Var1 Unit/1 Loc_3 27:11:2020 3
#> 16 3 Var3 Unit/3 Loc_3 25:11:2020 NA
#> 17 3 Var3 Unit/3 Loc_3 26:11:2020 NA
#> 18 3 Var3 Unit/3 Loc_3 27:11:2020 1
If you don't want one unique dataframe at the end, use map
instead of map_dfr
and remove , .id = "df"
Divide or split dataframe into multiple dfs based on empty row and header title
Maybe you can try
u <- rowSums(df == "")==ncol(df)
out <- split(subset(df,!u),cumsum(u)[!u])
which gives
> out
$`0`
V1 V2 V3 V4
1 Machine Data Editor
$`1`
V1 V2 V3 V4
3 Machine run information
4 V1 V2 V3 V4
5 03-09-2020 600119 6
$`2`
V1 V2 V3 V4
7 Machine error messages
8 No SpNo OP OP
9 Name
10 a a
11 1 b b
12 2 c c
$`3`
V1 V2 V3 V4
14 Machine logs
15 No sp op name
subsetting an R data.table delimited by empty rows
We can create a logical index with is.na
and Reduce
, convert it to numeric by doing the cumulative sum and split
the data into a list
of datasets
i1 <- dt[, Reduce(`&`, lapply(.SD, is.na))]
split(dt, cumsum(i1))
Split column maintaining empty values between delimiter R
You can try :
stringr::str_split(df$annotation, '|', fixed = TRUE, simplify = TRUE)
You also have tstrsplit
from data.table
package:
library(data.table)
setDT(df)
df[, tstrsplit(annotation, "|", fixed = TRUE)
How to repeat empty rows so that each split has the same number
Using data.table...
my_rows <- seq.int(max(tabulate(df$Initials)))
library(data.table)
setDT(df)[ , .SD[my_rows], by=Initials]
# Initials data
# 1: a 2
# 2: a 3
# 3: b 4
# 4: b NA
.SD
is the Subset of Data associated with each by=
group. We can subset its rows like .SD[row_numbers]
, unlike a data.frame which requires an additional comma DF[row_numbers,]
.
The analogue in dplyr is
my_rows <- seq.int(max(tabulate(df$Initials)))
library(dplyr)
setDT(df) %>% group_by(Initials) %>% slice(my_rows)
# Initials data
# (fctr) (dbl)
# 1 a 2
# 2 a 3
# 3 b 4
# 4 b NA
Strangely, this only works if df
is a data.table. I've filed a report/query with dplyr. There's a good chance that the dplyr devs will prevent this usage in a future version.
Split a dataframe into multiple dataframes based on specific row value in R
You are probably looking for the split
function. I made a small example where I split every time the b
column is equal to a
(d<-data.frame(a=1:10, b=sample(letters[1:3], replace = T, size = 10)))
#> a b
#> 1 1 a
#> 2 2 a
#> 3 3 c
#> 4 4 b
#> 5 5 c
#> 6 6 b
#> 7 7 c
#> 8 8 b
#> 9 9 c
#> 10 10 a
d$f<-cumsum(d$b=='a')
lst<-split(d, d$f)
lst
#> $`1`
#> a b f
#> 1 1 a 1
#>
#> $`2`
#> a b f
#> 2 2 a 2
#> 3 3 c 2
#> 4 4 b 2
#> 5 5 c 2
#> 6 6 b 2
#> 7 7 c 2
#> 8 8 b 2
#> 9 9 c 2
#>
#> $`3`
#> a b f
#> 10 10 a 3
Created on 2021-10-05 by the reprex package (v2.0.1)
Split a data.frame into smaller data.frames, based on the start and end indices (held in two vectors) and using a condition
Based on the answer to initial comment regarding row indices and using a similar 3-part approach like @Roland, the following should be what you want.
This creates a generic function to return all rows from "start" to "end" (assuming the provided elements are integers)
split_data <- function( start, end, dfr ){
dfr[start:end,]
}
This creates a list of ALL available splits.
split.frames <- mapply(split_data,START,END,MoreArgs=list(dfr=ALL_DATA))
This returns a logical vector with the i
th element equal to TRUE if the i
th split meets the desired condition.
cond <- sapply( split.frames, function(x){sum(x$Value)>=2} )
This returns only the splits that meet the condition.
split.frames <- split.frames[cond]
EDIT #1
Per the comment about saving off the splits, it is probably best to use the str_pad()
function from the R package stringr
for creating the file names, but here is a base R implementation that should work for you.
nchars <- nchar( length(split.frames) )
print.expr <- paste0("%0",nchars,"d")
for( i in 1:seq_along(split.frames) ){
file.i <- paste0( sprintf(print.expr,i), ".dat" )
write.table( split.frames[[i]], file=file.i, sep="\t", row.names=FALSE )
}
Not sure if you want column and/or row names in your saved outputs, but I assumed they were YES and NO respectively.
Split dataframe by row number follow by every specific row number count to create multiple data frames
I'll demonstrate on something a little smaller than 1e6 rows: mtcars
.
Let's say you want the frame split into no more than 10 rows each. Since it has 32 rows, this means we should have three frames with 10 rows each and one frame with 2 rows.
We'll use the %/%
integer (floor) division operator. It's important to note that we need the starting to start at 0
instead of R's default of 1
, so we will subtract 1.
(seq_len(nrow(mtcars)) - 1) %/% 10
# [1] 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
From here, just split on that:
out <- split(mtcars, (seq_len(nrow(mtcars)) - 1) %/% 10)
sapply(out, nrow)
# 0 1 2 3
# 10 10 10 2
out
# $`0`
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
# Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
# Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
# Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
# Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
# $`1`
# mpg cyl disp hp drat wt qsec vs am gear carb
# Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
# Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
# Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
# Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
# Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
# Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
# Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
# Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
# Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
# Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
# $`2`
# mpg cyl disp hp drat wt qsec vs am gear carb
# Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
# Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
# AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
# Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
# Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
# Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
# Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
# Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
# Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
# Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
# $`3`
# mpg cyl disp hp drat wt qsec vs am gear carb
# Maserati Bora 15.0 8 301 335 3.54 3.57 14.6 0 1 5 8
# Volvo 142E 21.4 4 121 109 4.11 2.78 18.6 1 1 4 2
There are several advantages of this technique:
- it is memory-efficient in that the
seq_len(.)
only counts as high as your frame has rows; it does not try to dorep(highnumber, highnumber)
, which will usually exceed R's memory when you have1e6
or so rows; - it directly controls which row goes into which group
- if you prefer your names to be 1-based, then add one, as in
(seq_len(.)-1) %/% 10 + 1
; if you want the names to be something else,names(out) <- c(...)
works, too
Another point: it is often much better in a sense to keep this in a list
instead of transferring it to the global environment: once you become more comfortable with lapply
and friends, it keeps your environment uncluttered, allows you to repeat one task for all frames in one motion (instead of copy/paste for each named variable), and is a very "canonical" approach to dealing with data (in R). See https://stackoverflow.com/a/24376207/3358227.
how to export dataframes from R to excel and separate them by an empty row
Using openxlsx
, which I hope works better for you than the other packages you mentioned, you can do:
library(openxlsx)
# create your workbook
mywb <- createWorkbook()
# create the sheets you need based on the first list of tables
for (sheetName in names(listofdfs)){
addWorksheet(mywb , sheetName )
}
# get all your lists of tables in a single list
l_listOfDF <- mget(ls(pattern="listofdf"))
# initiate the index of the row where you will want to start writing (one per sheet)
startR <- rep(1, length(listofdfs)) ; names(startR) <- names(listofdfs)
# loop over the lists of tables using index and then over the elements / sheets using their names
for(N_myListOfDF in seq(l_listOfDF)){
for(pageName in names(l_listOfDF[[N_myListOfDF]])){
# write the name/number of your table in the correct sheet, at the correct row
writeData(mywb, sheet=pageName, startRow=startR[pageName], paste0("Table ", N_myListOfDF, "."))
# write your data in the correct sheet at the correct row (the one after the name)
writeData(mywb, sheet=pageName, startRow=startR[pageName]+1, l_listOfDF[[N_myListOfDF]][[pageName]])
# update the row number (the + 3 is to leave space for name of table, headers and blank row
startR[pageName] <- startR[pageName]+nrow(l_listOfDF[[N_myListOfDF]][[pageName]]) + 3
}
}
# save your workbook in a file
saveWorkbook(mywb , "myfile.xlsx")
Output file:
Related Topics
How Can One Mix 2 or More Color Palettes to Show a Combined Color Value
How to Get Mean of Every N Rows and Keep the Date Index
Convert Month's Number to Month Name
Character "|" in Strsplit Function (Vertical Bar/Pipe)
R: Get the Min/Max of Each Item of a Vector Compared to Single Value
Change Line Color Depending on Y Value with Ggplot2
Downgrade R Version (No Issues with Bioconductor Installation)
Getting Table() to Return Zeroes in R
In R, How to Split Timestamp Interval Data into Regular Slots
Get Rows of Unique Values by Group
Error:Could Not Find Build Tools Necessary to Build
Highlight a Single "Bar" in Ggplot
Error: Could Not Find Build Tools Necessary to Build Dplyr
How to Automate Nested Sections in Rmds Which Include Text, Maps and Tables
Modify Spacing Between Key Glyphs in Vertical Legend Whilst Keeping Key Glyph Border
R Ggplot2 Using Italics and Non-Italics in the Same Category Label