r - How to make multiple file .txt from spesific column in data frame -
i have data frame contained 2 column, docs , text
docs text 1 tanaman jagung seumur jagung 2 tanaman jagung kacang ketimun rusak dimakan kelinci 3 ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan 4 ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan 5 ladang diserbu kelinci tanaman jagung kacang ketimun rusak
i want make multiple files .txts many number of id , every file containing different contents (every 1 txt file containing 1 row text in column of text). if have 5 docs-> 5 file .txt different content
i have tried code
for (j in 1:nrow(dataframe)) { mytitle <- format("docs") myfile <- file.path(getwd(), paste0(mytitle, "_", j, ".txt")) write.table(dataframe$text, file = myfile, sep = "", row.names = false, col.names = false, quote = false, append = false) }
but, results contained 5 file.txt each file has same content contained rows in column 'text'.
i suggest try following instead of using loops may confuse you
# create data frame docs <- c(1:5) text <- c("tanaman jagung seumur jagung " , "tanaman jagung kacang ketimun rusak dimakan kelinci" , "ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan" , "ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan" , "ladang diserbu kelinci tanaman jagung kacang ketimun rusak ") df <- data.frame(docs , text , test) # convert matrix m <- as.matrix(df) # create function write every single file write_file <- function(file){ my_title <- format("docs") file_name <- file.path(paste0( my_title , "_" , file[1] , ".txt")) file_content <- file[2] write.table(file_content , file = file_name , append = f , row.names = f , col.names = f , quote = f) } # use apply function pass each row in matrix # function creates every single file apply(m , 1 , write_file)
Comments
Post a Comment