Currently, I am a beginner who is conducting analysis using R, but due to unclear points,
Let me take this opportunity to ask you a question.
The compiler uses Rstudio.
The .CSV file is already loaded in the "Data" area where you can see the read data in the upper right corner.
There are 100 cases, but all have different names and I would like to add the name of the .CSV file to each column of data as a new item.I'd like to add this automatically using the for statement, but I don't know, so I'd like someone who knows more about it.
(Example)
a.csv
b.csv
c.csv
·
·
·
The contents of a (matrix) for
123456
A
B
C
D
If so, add the column name
name to the seventh column.
"I would like to store all the contents ""a"" in the seventh row."
I'd like to do all the same with a.csv, b.csv, c.csv.
library(tidyverse)
dir_path<- "YOUR_PATH"
files<-dir(path=dir_path, pattern=".csv", full.names=TRUE)# Get list of files in full path
file_names<-str_sub(string=basename(files), start=1, end=-5)# Get the non-extender portion of the filename
# processing with for
results<-NULL#Create a container for results
for(i in seq_along(file_names)){
result<-read_csv(files[i])
result$name<-file_names[i]
results[[i]]<-result
}
print(results)
Some approaches that use the tidyverse package are as follows:
map2 (.x=files, .y=file_names, .f=~read_csv(.x)%>%mute(name=.y))
© 2024 OneMinuteCode. All rights reserved.