워라밸 중독자

[R] 리스트를 데이터프레임으로 바꾸기 (리스트가 길이가 다른 벡터를 포함할 때) 본문

코딩, 딱 지금이 시작할때! (코딱지)

[R] 리스트를 데이터프레임으로 바꾸기 (리스트가 길이가 다른 벡터를 포함할 때)

Ufungi 2023. 10. 24. 11:56
# Create a list of vectors with different lengths
list_of_vectors <- list(
  A = c(1, 2, 3),
  B = c(4, 5, 6, 7),
  C = c(8, 9)
)

# Determine the maximum length in the list
max_length <- max(sapply(list_of_vectors, length))

# Fill shorter vectors with NA to make them equal in length
filled_list <- lapply(list_of_vectors, function(x) {
  if (length(x) < max_length) {
    c(x, rep(NA, max_length - length(x)))
  } else {
    x
  }
})

# Convert the filled list into a data frame
df <- do.call(data.frame, filled_list)

# Rename the columns if needed
colnames(df) <- names(list_of_vectors)

# Display the resulting data frame
print(df)