using a for loop to create new columns based on information in my rows

Hi everyone, I have a question about how to use a for loop to create new columns based on information I have in my rows. It seems easy but I am working with data where every row represents a follow up appointment. Every person has a follow up id (i.e. the follow up id is 1 in every row that corresponds to the same person) so there are duplicated people in the rows, but each row has new information on that specific person.

What I want is to have every row represent a person, but I can't just remove the duplicated ID's because I want to keep the information. So, is there a way to move the information from the rows into new columns that represent follow ups? (i.e. follow up 1 patient status, follow up 1 date, follow up 2 patient status, follow up 2 date, etc)

I currently have 10 columns in my data set and I know that is going to increase a lot if I do this. I'm sure I can use a nested for loop to do this but I am fairly new to R and am having a hard time conceptualizing exactly how to write this code. EDIT: If there is an easier way to do it than with a for loop I am open to it. I was just told by my professor that its possible to use a nested for loop!

below is a sample of the data I am working with, any help would be much appreciated. thank you so much!

data.frame(
COD = c(NA, NA, NA, 3399L, 999L),
DIAL_TY = c(1L, 1L, 1L, 1L, 1L),
FUNC_STAT = c(2060L, 2070L, 2070L, 2010L, 2L),
RETXDATE_KI = c(NA, NA, NA, NA, NA),
PT_CODE = c(59229L, 59229L, 59229L, 59229L, 207254L),
id = c(1L, 1L, 1L, 1L, 2L),
COD_OSTXT = as.factor(c(NA, NA, NA, "VIRAL PNEUMONIA",
"PULMONARY ASPIRATION OF GASTRIC CONTEN CONTENTS")),
DIABETES_DURING = as.factor(c("N", "N", "N", "N", NA)),
TRR_FOL_ID_CODE = as.factor(c("A1425848", "A1484622", "A3044285",
"A3206476", "A815384")),
PX_STAT_DATE = as.factor(c("05/19/2008", "11/10/2008", "11/09/2009",
"03/17/2010", "11/13/2000")),
TRR_ID_CODE = as.factor(c("A100", "A100", "A100", "A100", "A100001"))
)

Hi, welcome!

When working with R a for-loop is usually not the best option, to help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.