Filling an empty information box in R

I used the search box for this and found similar questions , but not identical. This seems to be a tricky issue though (I'm R-newbee).

I am just trying to create a new dataframe and add values ​​to it. Unsurprisingly, R throws an error saying the strings do not match.

Here's the code

d <- data.frame() 

files <- list.files(pattern="*.lst", full.names=T, recursive=FALSE)
d$fileName <- lapply(files, basename)
d$node <- gsub("([^.]+)\.[^\.lst]+\.lst", "$1", d$fileName, perl=TRUE)

      

And here's the mistake

Error in $<-.data.frame

( *tmp*

, "fileName", value = ("A-bom.WR-PEA.lst",: replacement has 337 lines, data 0

How can I solve this problem? I was thinking about filling with d

the same number of lines as files, but I don't think this is the best way?

0


source to share


1 answer


Just create your dataframe when it used the first time, so you don't add rows to the dataframe with zero rows. And you can use sapply

to return a vector (named) instead of a list.

files <- list.files(pattern="*.lst", full.names=T, recursive=FALSE)
d <- data.frame(fileName = unname(sapply(files, basename)))
d$node <- gsub("([^.]+)\\.[^\\.lst]+\\.lst", "$1", d$fileName, perl=TRUE)

      



Your regex caused an error, however, I'm not familiar with regex, so you may need to fix my corrections; -)

+1


source







All Articles