我有一个字符数组dat,我想将其转换为数据帧df,但它不起作用
head(dat)
[1] " 1931 1 5.0 0.6 11 78.4 43.4"
[2] " 1931 2 6.7 0.7 7 48.9 63.6"
[3] " 1931 4 10.4 3.1 3 44.6 110.1"
[4] " 1931 5 13.2 6.1 1 63.7 167.4"
[5] " 1931 6 15.4 8.0 0 87.8 150.3"
[6] " 1931 7 17.3 10.6 0 121.4 111.2"
> df<-as.data.frame(dat)
> head(df)
dat
1 1931 1 5.0 0.6 11 78.4 43.4
2 1931 2 6.7 0.7 7 48.9 63.6
3 1931 4 10.4 3.1 3 44.6 110.1
4 1931 5 13.2 6.1 1 63.7 167.4
5 1931 6 15.4 8.0 0 87.8 150.3
6 1931 7 17.3 10.6 0 121.4 111.2
df[,c(3)]
[.data.frame
(df,,c(3))中的错误:未定义的列已选中
答案 0 :(得分:1)
使用read.table
阅读:您可以根据需要rename
。
df<-read.table(text = " dat
1 1931 1 5.0 0.6 11 78.4 43.4
2 1931 2 6.7 0.7 7 48.9 63.6
3 1931 4 10.4 3.1 3 44.6 110.1
4 1931 5 13.2 6.1 1 63.7 167.4
5 1931 6 15.4 8.0 0 87.8 150.3
6 1931 7 17.3 10.6 0 121.4 111.2",
header=F,fill=T,as.is=T,skip = 1)
df[3]
V3
1 1
2 2
3 4
4 5
5 6
6 7
答案 1 :(得分:0)
如果dat
如结尾处的注释中可重复显示,则as.data.frame(dat)
创建一个数据框,其中包含一列称为dat
,然后尝试获取第三列由于只有一列,因此会导致错误。
相反,使用read.table
并获得第三列,如下所示。如果要获得数据帧结果,请省略逗号。
read.table(text = dat)[, 3]
## [1] 5.0 6.7 10.4 13.2 15.4 17.3
dat <- c(" 1931 1 5.0 0.6 11 78.4 43.4",
" 1931 2 6.7 0.7 7 48.9 63.6",
" 1931 4 10.4 3.1 3 44.6 110.1",
" 1931 5 13.2 6.1 1 63.7 167.4",
" 1931 6 15.4 8.0 0 87.8 150.3",
" 1931 7 17.3 10.6 0 121.4 111.2")
答案 2 :(得分:0)
这是一种 from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
# Define Image Transform
transform = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor()])
# Load Custom Image Dataset
dataset = datasets.ImageFolder(root="./Cat_Dog_data",
transform=transform)
# DataLoader
dataLoader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)
# Get one batch of Data
# len(images): 32
# len(labels): 32
# shape of images[0]: torch.Size([3, 224, 224])
images, labels = next(iter(dataLoader))
# img.shape: [224,224,3]
img = images[0].numpy().reshape([224, 224, 3])
plt.imshow(img)
plt.show()
的方法:
tidyverse
这导致:
dat <- c(" 1931 1 5.0 0.6 11 78.4 43.4",
" 1931 2 6.7 0.7 7 48.9 63.6",
" 1931 4 10.4 3.1 3 44.6 110.1",
" 1931 5 13.2 6.1 1 63.7 167.4",
" 1931 6 15.4 8.0 0 87.8 150.3",
" 1931 7 17.3 10.6 0 121.4 111.2")
library(tidyverse)
str_trim(dat) %>% # trim leading space
tibble(x = .) %>% # put into tibble (data.frame)
separate(x, # separate x into 7 columns, named below
into = c("year","v1","v2","v3","v4","v5","v6"),
sep = "[ ]{1,}") # separate by one or more spaces ("[ ]{1,}")