大佬教程收集整理的这篇文章主要介绍了用rstudio中的数据帧中的每个条目制作一个列表 数据数据,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 rstudio 中有一个数据框:
动物 | 颜色 | 重量 |
---|---|---|
鹿 | 棕色 | 小于3 |
猪 | 绿色 | 超过3个 |
我想要一个这样的列表:
我怎样才能做到这一点?现实生活中的应用程序有更多的条目和更多的特征,因此我喜欢一种自动化的方式。
谢谢!
如果我们有更多的列,那么一个选项是使用 across
来循环感兴趣的列,然后使用 glue
用当前列的值插入列 'Animal' 以及该列的列名 (cur_column()
)
library(dplyr)
df %>%
mutate(across(-Animal,~ glue::glue("{Animal}-{Cur_column()}: {.}"),.names = "{.col}_attributes"))
# Animal Color Weight Color_attributes Weight_attributes
#1 Deer Brown Less than 3 Deer-Color: Brown Deer-Weight: Less than 3
#2 Pig Green More than 3 Pig-Color: Green Pig-Weight: More than 3
df <- structure(list(Animal = c("Deer","Pig"),Color = c("Brown","Green"),Weight = c("Less than 3","More than 3")),class = "data.frame",row.names = c(NA,-2L))
,
在基础 R 中使用 apply
:
cols <- names(df)[-1]
apply(df,1,function(X) sprintf('%s-%s',x[1],paste(cols,x[-1],sep = ':')))
# [,1] [,2]
#[1,] "Deer-Color:Brown" "Pig-Color:Green"
#[2,] "Deer-Weight:Less than 3" "Pig-Weight:More than 3"
,
你想要一个像下面这样的列表吗?
> Map(as.list,split(df[-1],df[1]))
$Deer
$Deer$Color
[1] "Brown"
$Deer$Weight
[1] "Less than 3"
$Pig
$Pig$Color
[1] "Green"
$Pig$Weight
[1] "More than 3"
,
如果我理解正确,OP 希望输出以长格式重新整形(称为“列表”或“向量”)。
这是一种使用 $ time mawk2 'BEGIN { FS = "^$";
FILename = ARGV[ARGC-1];
cmd = "tail -c 2 \""FILename"\"";
cmd | getline XRS;
close(cmd);
RS = ( length(XRS) == 1 ) ? ORS : XRS ;
} { bytes += length } END {
print FILename " :: " bytes + NR * length(RS) }' genieMV_204583_1.mp4
genieMV_204583_1.mp4 :: 259105690
real 0m0.092s
m23lyricsRTM_Dict_15.txt :: 1961512986
real 0m0.950s
$ ls -AlnFT "${m3t}" genieMV_204583_1.mp4
-rw-r--r-- 1 501 20 1961512986 Mar 12 07:24:11 2021 m23lyricsRTM_Dict_15.txt
-r--r--r--@ 1 501 20 259105690 Jan 25 09:31:43 2021 genieMV_204583_1.mp4
和 @H_205_54@melt() 的可能方法。它适用于任意数量的属性列。
glue_data()
glue::glue_data(
data.table::melt(ds,id.var = "Animal"),"{Animal}-{variablE}: {value}")
或者,您可以使用 Deer-Color: Brown
Pig-Color: Green
Deer-Weight: Less than 3
Pig-Weight: More than 3
进行整形。
tidyr::pivot_longer()
,
我会把它分解成更小的问题。
import pandas as pd
from itertools import combinations
df = pd.read_csv('namen.csv',sep=";")
arr = ['name1','name2','name3']
r = 2
combs = [x for x in combinations(arr,2) ]
df_new = pd.DataFrame(columns=['A','B'])
for i in range(0,len(combs)-1):
df_temp = df[[combs[i][0],combs[i][1]]].copy()
df_temp.columns = df_new.columns
df_new = pd.concat([df_kanten,df_new],ignore_index=TruE)
以上是大佬教程为你收集整理的用rstudio中的数据帧中的每个条目制作一个列表 数据数据全部内容,希望文章能够帮你解决用rstudio中的数据帧中的每个条目制作一个列表 数据数据所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。