Kyla Celine Marcaida
Kyla Celine Marcaida

Reputation: 81

R - How to format text output from a list

I have the following dataframe:

  Name   Occupation    Country code   Remarks
  Mark   Engineer      1              Ok
  Jerry  Engineer      1              None
  Marie  Veterinarian  2              Ok
  Nolan  Veterinarian  2              Ok
  Max    Shepherd      2              Ok

I want to output the data frame into .txt files using the following codes:

df1 <- structure(list(Name = c("Mark", "Jerry", "Marie", "Nolan", "Max"), 
                 Occupation = c("Engineer", "Engineer", "Veterinarian",
                                "Veterinarian", "Shepherd"), 
                 Countrycode = c(1L, 1L, 2L, 2L, 2L), 
                                 Remarks = c("Ok", "None", "Ok", "Ok", "Ok")), 
                 class = "data.frame", row.names = c(NA, -5L))

df2 <- transform(df1, NameRemarks = paste(Name, Remarks, sep=" - "))
                 [, c("NameRemarks", "Occupation", "Countrycode")]

lst1 <- lapply(split(df2[-3], df2$Countrycode), 
           function(x) split(x['NameRemarks'], x$Occupation))

Map(capture.output, lst1, file = paste0("output", seq_along(lst1), ".txt"))

However, the output2.txt displays:

 $Shepherd
   NameRemarks
 5    Max - Ok

 $Veterinarian
   NameRemarks
 3  Marie - Ok
 4  Nolan - Ok

This is also the case with output1.txt. I want to clean the formatting into:

 Shepherd
 Max - Ok

 Veterinarian
 Marie - Ok
 Nolan - Ok

Upvotes: 1

Views: 127

Answers (1)

akrun
akrun

Reputation: 887831

In this case, we can do a single split, paste the 'Occupation' with the 'NameRemarks' column and cat to create new files

lst2 <- split(df2[-3], df2$Countrycode)
lapply(names(lst2), function(nm)  with(lst2[[nm]], {
  v1 <- tapply(NameRemarks, Occupation, FUN = paste, collapse="\n")
   cat(paste(names(v1), v1, sep="\n"), 
       file = paste0("output", nm, ".txt"), sep='\n\n')
   }))

-outputs

enter image description here

enter image description here

Upvotes: 1

Related Questions