how to read file with uneven number of columns in R

Welcome to the community!

Whenever you have a question on programming, first explore Stack Overflow. It's just great. I've provided an answer below based on a sample text file that I generated, but it is totally based on (just short of exact copy-paste) the accepted answer on this thread.

sample_text <- "3 -0.6693227 -0.7873222 0.4245348 1.2967424 0.3274851 -0.1359788 -1.6941693 -0.4211109 0.5652219 -0.9217692
9 -0.1666452 -2.4127623 -0.3542472 -0.3218811 0.1158014 0.4872717
6 -0.22941872 1.08753826 1.19390226 1.13897886 1.00118742 0.67274102 -0.03330435 -0.62604317 1.39810065 0.72696443
10 -1.23715047 -0.03268193 -2.10548252 -1.24928972 -1.77623106 -0.49554881
2 2.3935846  0.3702620 -0.8196183
7 -1.358423 1.751524
8 -0.2161822 0.5810251 0.5377655 -0.6070761 0.6760455 0.3222419 0.3980245 -0.9955221 .7672507 -0.7689794
1 -0.9068758
5 -0.5313554 0.2262915 -1.0024394 1.3053317 -0.6471348 0.7764412
4 -0.0239177"

read_the_text <- scan(text = sample_text, # if your data is in a text file, use the file argument
                      what = character(),
                      sep = "\n")

split_each_line_by_spaces <- strsplit(x = read_the_text,
                                      split = " ")

get_element_names <- lapply(X = split_each_line_by_spaces,
                            FUN = `[[`,
                            i = 1)

get_element_values <- lapply(X = split_each_line_by_spaces,
                             FUN = `[`,
                             i = (-1))

required_result_as_character <- setNames(object = get_element_values,
                                         nm = get_element_names)

required_result <- lapply(X = required_result_as_character,
                          FUN = as.numeric)

required_result
#> $`3`
#>  [1] -0.6693227 -0.7873222  0.4245348  1.2967424  0.3274851 -0.1359788
#>  [7] -1.6941693 -0.4211109  0.5652219 -0.9217692
#> 
#> $`9`
#> [1] -0.1666452 -2.4127623 -0.3542472 -0.3218811  0.1158014  0.4872717
#> 
#> $`6`
#>  [1] -0.22941872  1.08753826  1.19390226  1.13897886  1.00118742
#>  [6]  0.67274102 -0.03330435 -0.62604317  1.39810065  0.72696443
#> 
#> $`10`
#> [1] -1.23715047 -0.03268193 -2.10548252 -1.24928972 -1.77623106 -0.49554881
#> 
#> $`2`
#> [1]  2.3935846         NA  0.3702620 -0.8196183
#> 
#> $`7`
#> [1] -1.358423  1.751524
#> 
#> $`8`
#>  [1] -0.2161822  0.5810251  0.5377655 -0.6070761  0.6760455  0.3222419
#>  [7]  0.3980245 -0.9955221  0.7672507 -0.7689794
#> 
#> $`1`
#> [1] -0.9068758
#> 
#> $`5`
#> [1] -0.5313554  0.2262915 -1.0024394  1.3053317 -0.6471348  0.7764412
#> 
#> $`4`
#> [1] -0.0239177

Created on 2019-09-26 by the reprex package (v0.3.0)

Hope this helps.

1 Like