gpt4 book ai didi

旋转带有标题的数据框

转载 作者:行者123 更新时间:2023-12-03 23:08:14 24 4
gpt4 key购买 nike

我们如何将数据框更改或旋转为如下例所示(第一行表示标题)?

State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
Us 1980 FR 274 DE 641 UK 521

脚本:
State <- c("US", "FR","DE", "UK")
Customer <- c(1980, 274, 641, 521)

Table <- data.frame(State, Customer)

最佳答案

一个 base道路

df <- cbind.data.frame(split(Table, 1:nrow(Table)))
names(df) <- sub("(\\d+)\\.(\\D+)", "\\2\\1", names(df))

# State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
# 1 US 1980 FR 274 DE 641 UK 521

另一个选择使用 purrr::imap_dfc
library(purrr)
imap_dfc(split(Table, 1:nrow(Table)), ~ set_names(.x, paste0, .y))

# State1 Customer1 State2 Customer2 State3 Customer3 State4 Customer4
# 1 US 1980 FR 274 DE 641 UK 521

数据
Table <- structure(list(State = structure(c(4L, 2L, 1L, 3L), .Label = c("DE", 
"FR", "UK", "US"), class = "factor"), Customer = c(1980, 274,
641, 521)), class = "data.frame", row.names = c(NA, -4L))

关于旋转带有标题的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60902911/

24 4 0
文章推荐: python - Shap LSTM (Keras, TensorFlow) ValueError : shape mismatch: objects cannot be broadcast to a single shape
文章推荐: Python:计算并替换同一次正则表达式?
文章推荐: angular - NGRX:http 重试拦截器导致不触发失败操作
文章推荐: typescript :此表达式不可调用。类型 '{ getUserInfo(requestData: object): Promise; }' 没有调用签名