使用列名称中的id变量重新整形R [重复](Reshape with id-variable in column names R [duplicate])

这个问题在这里已有答案:

我已经和R一起工作了很长一段时间,但很少使用reshape或reshape2包。 我目前正在尝试从宽到长格式重塑数据集,其中指标变量是变量名称的一部分。 这是我数据框的当前结构:

mydf <- data.frame(district = c(1:2),
v.mandate = c(1, 3),
s.mandate = c(2, 4),
v.perc = c(.4, .3),
s.perc = c(.5, .6))

> mydf
  district v.mandate s.mandate v.perc s.perc
1        1         1         2    0.4    0.5
2        2         3         4    0.3    0.6

我想将其重新整理为长格式并提取“v”。 和“s。” 作为id变量(在实际数据集中,列表更长)。 见下面的例子。

mydf2 <- data.frame(district = c(1, 1, 2, 2),
party = c("v", "s", "v", "s"),
mandate = c(1, 2, 3, 4),
perc = c(.4, .5, .3, .6))

> mydf2
  district party mandate perc
1        1     v       1  0.4
2        1     s       2  0.5
3        2     v       3  0.3
4        2     s       4  0.6

我尝试过使用reshape和melt函数,但我似乎无法从变量名中提取指标变量。 而是将数据集重新整形为长格式,但将完整的变量名称作为id变量。 见下面的例子。

> melt(mydf, id.vars=1)
  district  variable value
1        1 v.mandate   1.0
2        2 v.mandate   3.0
3        1 s.mandate   2.0
4        2 s.mandate   4.0
5        1    v.perc   0.4
6        2    v.perc   0.3
7        1    s.perc   0.5
8        2    s.perc   0.6

这可能是一个微不足道的问题,但我无法在线找到解决方案。

非常感谢任何帮助!


This question already has an answer here:

I've worked with R for quite some time now, but have made little use of the reshape or reshape2 packages. I'm currently trying to reshape a data set from wide to long format where the indicator variables are part of the variable names. This is the current structure of my data frame:

mydf <- data.frame(district = c(1:2),
v.mandate = c(1, 3),
s.mandate = c(2, 4),
v.perc = c(.4, .3),
s.perc = c(.5, .6))

> mydf
  district v.mandate s.mandate v.perc s.perc
1        1         1         2    0.4    0.5
2        2         3         4    0.3    0.6

I want to reshape this to long format and extract the "v." and "s." as id variables (in the real data set the list is longer). See example below.

mydf2 <- data.frame(district = c(1, 1, 2, 2),
party = c("v", "s", "v", "s"),
mandate = c(1, 2, 3, 4),
perc = c(.4, .5, .3, .6))

> mydf2
  district party mandate perc
1        1     v       1  0.4
2        1     s       2  0.5
3        2     v       3  0.3
4        2     s       4  0.6

I have tried using both the reshape and melt functions, but I can't seem to extract the indicator variables from the variable names. Instead, the data set is reshaped into long format, but with the full variable names as id variables. See example below.

> melt(mydf, id.vars=1)
  district  variable value
1        1 v.mandate   1.0
2        2 v.mandate   3.0
3        1 s.mandate   2.0
4        2 s.mandate   4.0
5        1    v.perc   0.4
6        2    v.perc   0.3
7        1    s.perc   0.5
8        2    s.perc   0.6

It might be a trivial problem, but I haven't been able to find a solution on-line.

Greatly appreciate any help!


原文:https://stackoverflow.com/questions/29077443
2022-03-18 07:03

满意答案

 j = jet;
 j(1,:) = [ 1 1 1 ];
 colormap(j);
 imagesc(Img);

唯一的问题是图像中映射到最低颜色的任何其他东西也会变成白色。


 j = jet;
 j(1,:) = [ 1 1 1 ];
 colormap(j);
 imagesc(Img);

Only thing is that anything else in the image that maps to the lowest color is going to also come out white.

相关问答

更多

Matlab - 自动设置imagesc中的比例(Matlab - setting up the scale in imagesc automatically)

您可以使用caxis设置色阶的限制 img1 = randn(100); img2 = rand(100); %# find global min/max clim(1) = min(min(img1(:)),min(img2(:))); clim(2) = max(max(img1(:)),max(img2(:))); figure ah1 = axes; imagesc(img1) caxis(ah1,clim) %# show the other figure set the same...

在MATLAB中告诉imagesc使用特定的数字(Tell imagesc in MATLAB to use specific figure)

imagesc采用'parent'参数。 这是通过image功能间接记录的。 例如: imdata = imread('ngc6543a.jpg'); f = figure; a1 = subplot(211); a2 = subplot(212); image(imdata,'parent',a1); imagesc(imdata,'parent',a2); imagesc takes a 'parent' parameter. This is indirectly documented vi...

使用滑块实时更新imagesc的matlab(Matlab realtime updating of imagesc with a slider)

滑块可能具有非整数值。 在将其用作索引之前,您需要对其进行舍入 updateSystem(h, squeeze(T(round(es.Value), :, :))) 您可以使用以下内容作为回调来更新图像数据,而不是尝试使用updateSystem (控制系统工具箱功能)。 b.Callback = @(es, ed)set(h, 'CData', squeeze(T(round(es.Value), :, :))); It is possible for the slider to have ...

MATLAB:将imagesc()RESULT转换为图像(MATLAB: Convert imagesc() RESULT to an image)

%turn off the axes axis off %save the image saveas(h,'test.png') %read the saved image im_fft = imread('test.png'); %remove white border sum_img = sum(im_fft,3); sum_img(sum_img(:) ~= 255*3) = 0; sum_img = logical(sum_img); im_fft = im_fft(~all(sum_im...

MATLAB:imagesc()和image()以不同的方式显示相同的颜色表(MATLAB: imagesc() and image() display the same colormap differently)

imagesc缩放颜色轴,而image不缩放。 这就是为什么颜色看起来不同。 如果你点击彩条按钮,你会看到它们在不同的色阶上。 您可以使用caxis更改caxis 。 顺便说一下,如果您只想缩放X轴和Y轴,则可以使用任一功能。 只需提供您自己的缩放x和y矢量。 imagesc scales the color axis, whereas image does not. That's why the colors look different. If you click the colorbar b...

使用imwrite写出imagesc输出的真实颜色(Use imwrite to write true color of the output of imagesc)

这里是Cris Luengo方法的替代方法,它不依赖于imagesc生成的实际情节。 % load a test image I = rgb2gray(imread('peppers.png')); % recreate image cmap = colormap(); % grab current colormap ncolors = size(cmap,1); % do what imagesc does Iind = double(I) - double(min(I(:)...

imagesc在matlab中绘制到矩阵(imagesc plot to matrix in matlab)

imagesc的数据存储在CData属性中,因此使用它来提取它: X = get(h, 'CData'); 假设h是你的手柄。 现在X包含您的图像数据,您可以将其保存到文件中,例如: save somefile.mat X The data for imagesc is stored in the CData property, so use this to extract it: X = get(h, 'CData'); assuming h is your handle. Now X c...

matlab的imagesc背景颜色(matlab's imagesc background color)

j = jet; j(1,:) = [ 1 1 1 ]; colormap(j); imagesc(Img); 唯一的问题是图像中映射到最低颜色的任何其他东西也会变成白色。 j = jet; j(1,:) = [ 1 1 1 ]; colormap(j); imagesc(Img); Only thing is that anything else in the image that maps to the lowest color is going to also come o...

Matlab,如何获得imagesc生成的结果?(Matlab, How to get the result generated by imagesc?)

要以与imagesc相同的方式缩放图像,请执行以下操作 Amin = min(A(:)); Amax = max(A(:)); A_scaled = (A - Amin)/(Amax - Amin); 为了证明缩放的图像是图像在内部执行的操作,请尝试此操作 imagesc(A,[Amin Amax]); pause imagesc(A_scaled); To scale the image in the same way as imagesc do the following Amin = m...

更改imagesc图中像素的颜色,而不重新绘制Matlab / Octave中的所有内容(Change the color of a pixel in an imagesc plot without repainting everything in Matlab/Octave)

您可以使用图像的CData属性来处理每个像素中的数据,而无需一遍又一遍地关闭和重绘图形,轴或轴对象。 最终比尝试生成新的图像对象或只是反复调用imagesc()快1.5倍 - 2倍。 在这些循环中,不要忘记drawnow调用,否则MATLAB将尝试跳过图形绘制,直到循环完成。 示例代码: data = rand(200, 200); % Data to display figure(1) % Make a figure imgHand = imagesc(data); % Display dat...

相关文章

更多

nutch与起点R3集成之笔记(四)

通过“nutch与起点R3集成之笔记(一、二、三)”中的步骤,我们可以建立起一个行业内部网的搜索引擎, ...

nutch与起点R3集成之笔记(一)

百度、google帮我们找Internet的信息,但对于一个行业内部网(intranet)来说,百度、 ...

nutch与起点R3集成之笔记(二)

在nutch与起点R3集成之笔记(一)中介绍了在起点R3中添加nutch要用到的索引字段,上述字段建好 ...

R语言实战视频教程-尚学堂视频教程

主讲老师系985高校计算机博士,有丰富的大数据、云计算的教学和实战经验。 作为当前在世界范围内最受欢迎 ...

R简单数据分析

眼下大数据口号满天飞,今天拿我微信圈朋友一段时间内分享内容作为数据,用R包的算法实现简单分析。 由于微 ...

在Hadoop集群上运行R程序--安装RHadoop

Hadoop是由Revolution Analytics发起的一个开源项目,它可以将统计语言R与Had ...

Apache Solr 实现去掉重复的搜索结果

  打上SOLR-236_collapsing.patch补丁,实现 solr 搜索结果折叠、除去重复 ...

请问起点R3能否做到完全支持MultiCore?

在RivuSchema类中实现了从数据库获取数据类型和索引结构表中的数据构建Schema.xml,但这 ...

nutch与起点R3集成之笔记(三)

四、抓取网页,建立solr索引 在抓取网页前,要保证起点R3处在运行状态。即 在浏览器中键入 http ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本