It looks like there is no row.names=file.names[i]
option when I use the write.table
function. For example, assuming in the folder I've 3 files named "file_1", "file_2", and "file_3", then in the output csv
file, I would like to see the following results:
"","keyword","totalword"
"file_1",10,4348
"file_2",1,1635
"file_3",1,3237
for(i in 1:length(file.names)){
## calculate number of keywords and total words for each file within a folder
x <- data.frame(keyword,totalword)
write.csv(x, file="results.csv",row.names = TRUE)
}
Using the above code, all I can get is the following:
"","keyword","totalword"
"1",10,4348
"2",1,1635
"3",1,3237
Anyone knows how to specify the row name using the name of each original file (ie, changing "1" "2" "3" to "file_1", "file_2, "file_3"?
You have the names of the files in 'file.names' so just changex <- data.frame(keyword,totalword)
to x <- data.frame(file.names[i],keyword,totalword)
You may have to get rid of the row.names = TRUE
.
With those data :
keyword<-c(10,1,1)
totalword<-c(4348,1635,3237)
Here are a few options :
x<-data.frame(keyword,totalword,row.names=paste0('file_',1:3))
write.csv(x, file="results.csv",row.names = TRUE)
or
x<-data.frame(keyword,totalword)
rownames(x)<-paste0('file_',1:3)
write.csv(x, file="results.csv",row.names = TRUE)
or
write.csv(x,file="results.csv",row.names=paste0('file_',1:3))
all of these will return that in the CSV file :
"","keyword","totalword"
"file_1",10,4348
"file_2",1,1635
"file_3",1,3237
I assumed that you have the 3 rows and that you then write a csv. If you want to write one line in the csv then the next one and so on (one line for each iteration) you could do something like :
write.csv(x,file="results.csv",append=TRUE,row.names=paste0('file_',i))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.